﻿define(['moment', 'sortablejs'], function (moment, Sortable) {
    return ['$scope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', '$datePicker', '$timeout', "$state",
    function ($scope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $datePicker, $timeout, $state) {

        //^_^ADD BY H-18036  20221129 FOR 
        $scope.value_e = moment($scope.work_date).add(0, 'd').toDate();
        $scope.value_s = moment($scope.work_date).add(-2, 'd').toDate();
        $scope.do_flag = 1; //0是1否
        $scope.QueryLotInfo = [];
        $scope.op_group_detail = [];
        //-----------------------------------------
        $scope.Mode = '';
        $scope.machineList = [];//區域內的機台列表
        $scope.machine_detail = [];
        $scope.PageConfig = { page: 0, page_count: 25 };
        $scope.dispatch_filter = {};
        $scope.is_lock_sort = false;
        $scope.select_all_bool = false;
        $scope.roll_back_all_bool = false;
        $scope.order_by_mode = { name: "", sort: false };
        $scope.assigned_machine = ''; // 過濾已派工的設備編號或設備名稱
        $scope.assigned_wo_no = ''; 
        $scope.assigned_plot_no = '';
        $scope.acc_detail = [];
        $scope.ht_tr_bool = false; //M#95547 add by a991241234 熱處理 是否顯示爐量

        $scope.equipment_sort_option_list =
        [{ label: $filter('translate')('A02.equipment_sort_list.option_0'), code: "0" },
        { label: $filter('translate')('A02.equipment_sort_list.option_1'), code: "1" },
        { label: $filter('translate')('A02.equipment_sort_list.option_2'), code: "2" },
        { label: $filter('translate')('A02.equipment_sort_list.option_3'), code: "3" },
        { label: $filter('translate')('A02.equipment_sort_list.option_4'), code: "4" },
        { label: $filter('translate')('A02.equipment_sort_list.option_5'), code: "5" },
        { label: $filter('translate')('A02.equipment_sort_list.option_6'), code: "6" },
        { label: $filter('translate')('A02.equipment_sort_list.option_7'), code: "7" }]

        $scope.equipment_sort_mode_label = $scope.equipment_sort_option_list[0].label;
        $scope.equipment_sort_mode = $scope.equipment_sort_option_list[0].code;
        $scope.equipment_sort_mode_change = false;
        $scope.product_detail = [];

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.area_detail = [];
        $scope.selectareaNo = "";
        $scope.isLine = "";
        $scope.selectWorkStation = '';
        $scope.selectWorkStationName = '';

        $scope.init = function () { 

            if($stateParams.data.hasOwnProperty('machine')){
                // 20230308 modify by shilw 多日派工跳转到派工调整带入入参  区域 ,作业站 、设备，日期、工单号、生产批号
                $scope.selectareaName = $stateParams.data.machine; 
               //  assigned_wo_no 工单号，assigned_plot_no 生产批号，assigned_machine设备
                $scope.selectWorkStationName = $stateParams.selectWorkStationName;

                $scope.workDate = $stateParams.data.machine.work_date;
             
              //  $scope.assigned_machine = $stateParams.data.assigned_machine;
                $scope.assigned_plot_no = $stateParams.data.assigned_plot_no;
                $scope.assigned_wo_no = $stateParams.data.assigned_wo_no;
               
                $scope.selectareaName = $stateParams.data.selectareaName;

               // $scope.selectWorkStationName =$stateParams.data.selectWorkStationName;
               $scope.selectWorkStationName = '';
                if($stateParams.data.hasOwnProperty('lst_opno')){
                        $stateParams.data.lst_opno.forEach(function (item) {
                                if (item.is_select == 'true'){
                                        $scope.selectWorkStationName += item.op_name + ' \\ ';
                                        $scope.op_group_detail.push(item);
                                }
                                   
                               
                            });
                   }

                $scope.value_e = moment($scope.workDate);
                $scope.value_s =  moment($scope.workDate);
               
            }
        
            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            $scope.showMode = "query"
            $scope.printList = []; // 列印詳情

            $MMWService.PNIGList = {};
            $scope.work_date = new Date();//工作時間
            $scope.order_by_mode = { name: "", sort: false };
            // 20201221 FOR 83491 自定义排版
            // 派工
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.settingList = [
                'op_no', 'op_name', 'wo_no', 'plot_no', 'qty', 'plot_start_time', 'plot_end_time', 'item_no', 'item_name', 'item_spec', 'mono_date', 'accessory_no',
                'item_version', 'BaseProcessNo', 'BaseProcessVersion', 'BoxQty', 'CUSTOMERNO', 'CartonQty', 'ERPMoLineNo', 'FACTORYNO', 'GRAPHNO', 'HotLot', 'ITEMNO', 'LOTDescription', 'LOTPriority',
                'LOTSTDQty', 'LOTplanstartdate', 'MOPRIORITY', 'MOUNITNO', 'MOplanstartdate', 'MPQty', 'MoDescription', 'MoSource', 'MoUser_Defined01', 'MoUser_Defined02', 'MoUser_Defined03', 'MoUser_Defined04', 'MoUser_Defined05',
                'MoUser_Defined11', 'MoUser_Defined12', 'MoUser_Defined13', 'MoUser_Defined21', 'MoUser_Defined22', 'MoUser_Defined23', 'PRODUCTTYPE', 'PalletQty', 'PrdDescription', 'PrdUser_Defined01',
                'PrdUser_Defined02', 'PrdUser_Defined03', 'PrdUser_Defined04', 'PrdUser_Defined05', 'PrdUser_Defined11', 'PrdUser_Defined12', 'PrdUser_Defined13', 'PrdUser_Defined21', 'PrdUser_Defined22',
                'PrdUser_Defined23', 'PriceType', 'ProductCode', 'ProductPCSNo', 'QCCategory', 'RONO', 'SerialTypeNo_COMP', 'SerialTypeNo_LOT', 'SpecNo', 'StockInLotNo', 'Storage_Spaces_No', 'Warehouse_No'
            ];
            // 已派工
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.dispatchedSettingList = [
                'op_no', 'op_name', 'wo_no', 'plot_no', 'plot_qty', 'uncheck_in_qty', 'plot_start_time', 'plot_end_time', 'dis_start_time', 'disp_end_time', 'item_no', 'item_name', 'batch_mark', 'item_spec', 'tc_rate', 'tc_rate_for_all', 'c_rate_for_all', 'mono_date',
                'MOplanstartdate', 'CUSTOMERNO', 'RONO', 'ITEMNO', 'MOPRIORITY', 'MOUNITNO', 'MoDescription', 'MoSource', 'FACTORYNO', 'StockInLotNo', 'Warehouse_No', 'Storage_Spaces_No', 'ERPMoLineNo',
                'MoUser_Defined01', 'MoUser_Defined02', 'MoUser_Defined03', 'MoUser_Defined04', 'MoUser_Defined05', 'MoUser_Defined11', 'MoUser_Defined12', 'MoUser_Defined13', 'MoUser_Defined21', 'MoUser_Defined22', 'MoUser_Defined23',
                'PRODUCTTYPE', 'SpecNo', 'GRAPHNO', 'PrdDescription', 'CartonQty', 'PalletQty', 'BoxQty', 'ProductCode', 'SerialTypeNo_LOT', 'SerialTypeNo_COMP', 'LOTSTDQty', 'PrdUser_Defined01', 'PrdUser_Defined02', 'PrdUser_Defined03',
                'PrdUser_Defined04', 'PrdUser_Defined05', 'PrdUser_Defined11', 'PrdUser_Defined12', 'PrdUser_Defined13', 'PrdUser_Defined21', 'PrdUser_Defined22', 'PrdUser_Defined23', 'QCCategory', 'ProductPCSNo', 'MPQty', 'LOTPriority',
                'HotLot', 'LOTDescription', 'LOTplanstartdate', 'PriceType', 'BaseProcessNo', 'BaseProcessVersion'
            ];
            $scope.packList = [];
            $scope.moreInfoList = [];
            $scope.showTipsFlag = false;
            $scope.tempRow = {};
            $scope.tempDispatchRow = {};

            $scope.dispatchedPackList = [];
            $scope.dispatchedMoreInfoList = [];
            $scope.dispatchedShowTipsFlag = false;
            $scope.dispatchedTempRow = {};

            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.show_flag = {
                op_no: false,
                op_name: false,
                wo_no: false,
                plot_no: false,
                qty: false,
                plot_start_time: false,
                plot_end_time: false,
                item_no: false,
                item_name: false,
                item_spec: false,
                mono_date: false,
                accessory_no: false,
                item_version: false,
                BaseProcessNo: false,
                BaseProcessVersion: false,
                BoxQty: false,
                CUSTOMERNO: false,
                CartonQty: false,
                ERPMoLineNo: false,
                FACTORYNO: false,
                GRAPHNO: false,
                HotLot: false,
                ITEMNO: false,
                LOTDescription: false,
                LOTPriority: false,
                LOTSTDQty: false,
                LOTplanstartdate: false,
                MOPRIORITY: false,
                MOUNITNO: false,
                MOplanstartdate: false,
                MPQty: false,
                MoDescription: false,
                MoSource: false,
                MoUser_Defined01: false,
                MoUser_Defined02: false,
                MoUser_Defined03: false,
                MoUser_Defined04: false,
                MoUser_Defined05: false,
                MoUser_Defined11: false,
                MoUser_Defined12: false,
                MoUser_Defined13: false,
                MoUser_Defined21: false,
                MoUser_Defined22: false,
                MoUser_Defined23: false,
                PRODUCTTYPE: false,
                PalletQty: false,
                PrdDescription: false,
                PrdUser_Defined01: false,
                PrdUser_Defined02: false,
                PrdUser_Defined03: false,
                PrdUser_Defined04: false,
                PrdUser_Defined05: false,
                PrdUser_Defined11: false,
                PrdUser_Defined12: false,
                PrdUser_Defined13: false,
                PrdUser_Defined21: false,
                PrdUser_Defined22: false,
                PrdUser_Defined23: false,
                PriceType: false,
                ProductCode: false,
                ProductPCSNo: false,
                QCCategory: false,
                RONO: false,
                SerialTypeNo_COMP: false,
                SerialTypeNo_LOT: false,
                SpecNo: false,
                StockInLotNo: false,
                Storage_Spaces_No: false,
                Warehouse_No: false
            };
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.dispatched_show_flag = {
                op_no: false,
                op_name: false,
                wo_no: false,
                plot_no: false,
                plot_qty: false,
                uncheck_in_qty: false,
                plot_start_time: false,
                plot_end_time: false,
                dis_start_time: false,
                disp_end_time: false,
                item_no: false,
                item_name: false,
                batch_mark: false,
                item_spec: false,
                tc_rate: false,
                tc_rate_for_all: false,
                c_rate_for_all: false,
                mono_date: false,
                MOplanstartdate: false,
                CUSTOMERNO: false,
                RONO: false,
                ITEMNO: false,
                MOPRIORITY: false,
                MOUNITNO: false,
                MoDescription: false,
                MoSource: false,
                FACTORYNO: false,
                StockInLotNo: false,
                Warehouse_No: false,
                Storage_Spaces_No: false,
                ERPMoLineNo: false,
                MoUser_Defined01: false,
                MoUser_Defined02: false,
                MoUser_Defined03: false,
                MoUser_Defined04: false,
                MoUser_Defined05: false,
                MoUser_Defined11: false,
                MoUser_Defined12: false,
                MoUser_Defined13: false,
                MoUser_Defined21: false,
                MoUser_Defined22: false,
                MoUser_Defined23: false,
                PRODUCTTYPE: false,
                SpecNo: false,
                GRAPHNO: false,
                PrdDescription: false,
                CartonQty: false,
                PalletQty: false,
                BoxQty: false,
                ProductCode: false,
                SerialTypeNo_LOT: false,
                SerialTypeNo_COMP: false,
                LOTSTDQty: false,
                PrdUser_Defined01: false,
                PrdUser_Defined02: false,
                PrdUser_Defined03: false,
                PrdUser_Defined04: false,
                PrdUser_Defined05: false,
                PrdUser_Defined11: false,
                PrdUser_Defined12: false,
                PrdUser_Defined13: false,
                PrdUser_Defined21: false,
                PrdUser_Defined22: false,
                PrdUser_Defined23: false,
                QCCategory: false,
                ProductPCSNo: false,
                MPQty: false,
                LOTPriority: false,
                HotLot: false,
                LOTDescription: false,
                LOTplanstartdate: false,
                PriceType: false,
                BaseProcessNo: false,
                BaseProcessVersion: false
            };
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.show_label = {
                op_no: '',
                op_name: '',
                wo_no: '',
                plot_no: '',
                qty: '',
                plot_start_time: '',
                plot_end_time: '',
                item_no: '',
                item_name: '',
                item_spec: '',
                mono_date: '',
                accessory_no: '',
                item_version: '',
                BaseProcessNo: '',
                BaseProcessVersion: '',
                BoxQty: '',
                CUSTOMERNO: '',
                CartonQty: '',
                ERPMoLineNo: '',
                FACTORYNO: '',
                GRAPHNO: '',
                HotLot: '',
                ITEMNO: '',
                LOTDescription: '',
                LOTPriority: '',
                LOTSTDQty: '',
                LOTplanstartdate: '',
                MOPRIORITY: '',
                MOUNITNO: '',
                MOplanstartdate: '',
                MPQty: '',
                MoDescription: '',
                MoSource: '',
                MoUser_Defined01: '',
                MoUser_Defined02: '',
                MoUser_Defined03: '',
                MoUser_Defined04: '',
                MoUser_Defined05: '',
                MoUser_Defined11: '',
                MoUser_Defined12: '',
                MoUser_Defined13: '',
                MoUser_Defined21: '',
                MoUser_Defined22: '',
                MoUser_Defined23: '',
                PRODUCTTYPE: '',
                PalletQty: '',
                PrdDescription: '',
                PrdUser_Defined01: '',
                PrdUser_Defined02: '',
                PrdUser_Defined03: '',
                PrdUser_Defined04: '',
                PrdUser_Defined05: '',
                PrdUser_Defined11: '',
                PrdUser_Defined12: '',
                PrdUser_Defined13: '',
                PrdUser_Defined21: '',
                PrdUser_Defined22: '',
                PrdUser_Defined23: '',
                PriceType: '',
                ProductCode: '',
                ProductPCSNo: '',
                QCCategory: '',
                RONO: '',
                SerialTypeNo_COMP: '',
                SerialTypeNo_LOT: '',
                SpecNo: '',
                StockInLotNo: '',
                Storage_Spaces_No: '',
                Warehouse_No: ''
            };
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.dispatched_show_label = {
                op_no: '',
                op_name: '',
                wo_no: '',
                plot_no: '',
                plot_qty: '',
                uncheck_in_qty: '',
                plot_start_time: '',
                plot_end_time: '',
                dis_start_time: '',
                disp_end_time: '',
                item_no: '',
                item_name: '',
                batch_mark: '',
                item_spec: '',
                tc_rate: '',
                tc_rate_for_all: '',
                c_rate_for_all: '',
                mono_date: '',
                MOplanstartdate: '',
                CUSTOMERNO: '',
                RONO: '',
                ITEMNO: '',
                MOPRIORITY: '',
                MOUNITNO: '',
                MoDescription: '',
                MoSource: '',
                FACTORYNO: '',
                StockInLotNo: '',
                Warehouse_No: '',
                Storage_Spaces_No: '',
                ERPMoLineNo: '',
                MoUser_Defined01: '',
                MoUser_Defined02: '',
                MoUser_Defined03: '',
                MoUser_Defined04: '',
                MoUser_Defined05: '',
                MoUser_Defined11: '',
                MoUser_Defined12: '',
                MoUser_Defined13: '',
                MoUser_Defined21: '',
                MoUser_Defined22: '',
                MoUser_Defined23: '',
                PRODUCTTYPE: '',
                SpecNo: '',
                GRAPHNO: '',
                PrdDescription: '',
                CartonQty: '',
                PalletQty: '',
                BoxQty: '',
                ProductCode: '',
                SerialTypeNo_LOT: '',
                SerialTypeNo_COMP: '',
                LOTSTDQty: '',
                PrdUser_Defined01: '',
                PrdUser_Defined02: '',
                PrdUser_Defined03: '',
                PrdUser_Defined04: '',
                PrdUser_Defined05: '',
                PrdUser_Defined11: '',
                PrdUser_Defined12: '',
                PrdUser_Defined13: '',
                PrdUser_Defined21: '',
                PrdUser_Defined22: '',
                PrdUser_Defined23: '',
                QCCategory: '',
                ProductPCSNo: '',
                MPQty: '',
                LOTPriority: '',
                HotLot: '',
                LOTDescription: '',
                LOTplanstartdate: '',
                PriceType: '',
                BaseProcessNo: '',
                BaseProcessVersion: '',
            };
            if (localStorage.getItem('customLayout')) {
                var settingsList = JSON.parse(localStorage.getItem('customLayout'));
                var settingsIdx = settingsList.findIndex(function (item) {
                    return item.page_id == 'WIP007' && item.div_id == 'undsplist';
                });
                if (settingsIdx !== -1 && settingsList[settingsIdx].view_desc) {
                    let tempList = JSON.parse(settingsList[settingsIdx].view_desc).data;
                    tempList.forEach(t => {
                        $scope.packList.push(t.col[0]);
                    });
                    $scope.moreInfoList = JSON.parse(settingsList[settingsIdx].view_desc).list;
                }
                if ($scope.packList.length > 0) {
                    $scope.packList.forEach(p => {
                        let data = $scope.settingList.filter(l => p.fieldId == l);
                        if (data.length > 0) {
                            $scope.show_flag[p.fieldId] = true;
                            $scope.show_label[p.fieldId] = p.fieldName;
                        }
                    });
                } else {
                    $scope.getInitData();
                }

                //^_^ADD BY H-18036  20221201 FOR 
                //$scope.QueryLotInfo_show_label();
                //$scope.QueryLotInfo_show_label = {
                //    WORKDATE: '',
                //    OPNO: '',
                //    OPNAME: '',
                //    EQUIPMENTNO: '',
                //    EQUIPMENTNAME: '',
                //    LotNo: '',
                //    Qty: '',
                //    ProductNo: '',
                //    ProductName: '',
                //    ItemSpec: '',
                //    CombinedTag: '',
                //    StdDispStartTime: '',
                //    StdDispEndTime: '',
                //    DispStartTime: '',
                //    DispEndTime: '',
                //    monodate: '',
                //};
                //$scope.QueryLotInfo_show_label = function () {
                //    $scope.QueryLotInfo_show_label.WORKDATE = $filter('translate')('A10.list_head.column1'),
                //    $scope.QueryLotInfo_show_label.OPNO = $filter('translate')('A10.list_head.column2'),
                //    $scope.QueryLotInfo_show_label.OPNAME = $filter('translate')('A10.list_head.column3'),
                //    $scope.QueryLotInfo_show_label.EQUIPMENTNO = $filter('translate')('A10.list_head.column4'),
                //    $scope.QueryLotInfo_show_label.EQUIPMENTNAME = $filter('translate')('A10.list_head.column5'),
                //    $scope.QueryLotInfo_show_label.LotNo = $filter('translate')('A10.list_head.column6'),
                //    $scope.QueryLotInfo_show_label.Qty = $filter('translate')('A10.list_head.column7'),
                //    $scope.QueryLotInfo_show_label.ProductNo = $filter('translate')('A10.list_head.column8'),
                //    $scope.QueryLotInfo_show_label.ProductName = $filter('translate')('A10.list_head.column9'),
                //    $scope.QueryLotInfo_show_label.ItemSpec = $filter('translate')('A10.list_head.column10'),
                //    $scope.QueryLotInfo_show_label.CombinedTag = $filter('translate')('A10.list_head.column11'),
                //    $scope.QueryLotInfo_show_label.StdDispStartTime = $filter('translate')('A10.list_head.column12'),
                //    $scope.QueryLotInfo_show_label.StdDispEndTime = $filter('translate')('A10.list_head.column13'),
                //    $scope.QueryLotInfo_show_label.DispStartTime = $filter('translate')('A10.list_head.column14'),
                //    $scope.QueryLotInfo_show_label.DispEndTime = $filter('translate')('A10.list_head.column15'),
                //    $scope.QueryLotInfo_show_label.monodate = $filter('translate')('A10.list_head.column16')
                //};



                // 已派工
                var dispatchedSettingsIdx = settingsList.findIndex(function (item) {
                    return item.page_id == 'WIP007' && item.div_id == 'ondsplist';
                });
                if (dispatchedSettingsIdx !== -1 && settingsList[dispatchedSettingsIdx].view_desc) {
                    let tempList = JSON.parse(settingsList[dispatchedSettingsIdx].view_desc).data;
                    tempList.forEach(t => {
                        $scope.dispatchedPackList.push(t.col[0]);
                    });
                    $scope.dispatchedMoreInfoList = JSON.parse(settingsList[dispatchedSettingsIdx].view_desc).list;
                }
                if ($scope.dispatchedPackList.length > 0) {
                    $scope.dispatchedPackList.forEach(p => {
                        let data = $scope.dispatchedSettingList.filter(l => p.fieldId == l);
                        if (data.length > 0) {
                            $scope.dispatched_show_flag[p.fieldId] = true;
                            $scope.dispatched_show_label[p.fieldId] = p.fieldName;
                        }
                    });
                } else {
                    $scope.getDispatchedInitData();
                }
            } else {
                $scope.getInitData();
                $scope.getDispatchedInitData();
            }
            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            // step 1. 取得區域
            $scope.loadAreaInfo();
           
       
        };

        // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
        $scope.getInitData = function () {
            $scope.show_flag.op_no = true;
            $scope.show_flag.op_name = true;
            $scope.show_flag.wo_no = true;
            $scope.show_flag.plot_no = true;
            $scope.show_flag.qty = true;
            $scope.show_flag.plot_start_time = true;
            $scope.show_flag.plot_end_time = true;
            $scope.show_flag.item_no = true;
            $scope.show_flag.item_name = true;
            $scope.show_flag.item_spec = true;
            $scope.show_flag.mono_date = true;
            $scope.show_flag.accessory_no = true;
            $scope.show_label.op_no = $filter('translate')('A02.list.column1');
            $scope.show_label.op_name = $filter('translate')('A02.list.column2');
            $scope.show_label.wo_no = $filter('translate')('A02.list.column12');
            $scope.show_label.plot_no = $filter('translate')('A02.list.column3');
            $scope.show_label.qty = $filter('translate')('A02.list.column4');
            $scope.show_label.plot_start_time = $filter('translate')('A02.list.column7');
            $scope.show_label.plot_end_time = $filter('translate')('A02.list.column8');
            $scope.show_label.item_no = $filter('translate')('A02.list.column5');
            $scope.show_label.item_name = $filter('translate')('A02.list.column6');
            $scope.show_label.item_spec = $filter('translate')('A02.list.column13');
            $scope.show_label.mono_date = $filter('translate')('A02.list.column16');
            $scope.show_label.accessory_no = $filter('translate')('A02.list.column17');
        };

        // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
        $scope.getDispatchedInitData = function () {
            $scope.dispatched_show_flag.op_no = true,
            $scope.dispatched_show_flag.op_name = true,
            $scope.dispatched_show_flag.wo_no = true,
            $scope.dispatched_show_flag.plot_no = true,
            $scope.dispatched_show_flag.plot_qty = true,
            $scope.dispatched_show_flag.uncheck_in_qty = true,
            $scope.dispatched_show_flag.plot_start_time = true,
            $scope.dispatched_show_flag.plot_end_time = true,
            $scope.dispatched_show_flag.dis_start_time = true,
            $scope.dispatched_show_flag.disp_end_time = true,
            $scope.dispatched_show_flag.item_no = true,
            $scope.dispatched_show_flag.item_name = true,
            $scope.dispatched_show_flag.batch_mark = true,
            $scope.dispatched_show_flag.item_spec = true,
            $scope.dispatched_show_flag.tc_rate = true,
            $scope.dispatched_show_flag.tc_rate_for_all = true,
            $scope.dispatched_show_flag.c_rate_for_all = true,
            $scope.dispatched_show_flag.mono_date = true,
            $scope.dispatched_show_label.op_no = $filter('translate')('customLayout.ondsplist.column0'),
            $scope.dispatched_show_label.op_name = $filter('translate')('customLayout.ondsplist.column1'),
            $scope.dispatched_show_label.wo_no = $filter('translate')('customLayout.ondsplist.column2'),
            $scope.dispatched_show_label.plot_no = $filter('translate')('customLayout.ondsplist.column3'),
            $scope.dispatched_show_label.plot_qty = $filter('translate')('customLayout.ondsplist.column4'),
            $scope.dispatched_show_label.uncheck_in_qty = $filter('translate')('customLayout.ondsplist.column5'),
            $scope.dispatched_show_label.plot_start_time = $filter('translate')('customLayout.ondsplist.column6'),
            $scope.dispatched_show_label.plot_end_time = $filter('translate')('customLayout.ondsplist.column7'),
            $scope.dispatched_show_label.dis_start_time = $filter('translate')('customLayout.ondsplist.column8'),
            $scope.dispatched_show_label.disp_end_time = $filter('translate')('customLayout.ondsplist.column9'),
            $scope.dispatched_show_label.item_no = $filter('translate')('customLayout.ondsplist.column10'),
            $scope.dispatched_show_label.item_name = $filter('translate')('customLayout.ondsplist.column11'),
            $scope.dispatched_show_label.batch_mark = $filter('translate')('customLayout.ondsplist.column12'),
            $scope.dispatched_show_label.item_spec = $filter('translate')('customLayout.ondsplist.column13'),
            $scope.dispatched_show_label.tc_rate = $filter('translate')('customLayout.ondsplist.column14'),
            $scope.dispatched_show_label.tc_rate_for_all = $filter('translate')('customLayout.ondsplist.column15'),
            $scope.dispatched_show_label.c_rate_for_all = $filter('translate')('customLayout.ondsplist.column16'),
            $scope.dispatched_show_label.mono_date = $filter('translate')('customLayout.ondsplist.column19'),
                    $scope.dispatched_show_label.WORKDATE = $filter('translate')('A10.list_head.column1'),
                    $scope.dispatched_show_label.OPNO = $filter('translate')('A10.list_head.column2'),
                    $scope.dispatched_show_label.OPNAME = $filter('translate')('A10.list_head.column3'),
                    $scope.dispatched_show_label.EQUIPMENTNO = $filter('translate')('A10.list_head.column4'),
                    $scope.dispatched_show_label.EQUIPMENTNAME = $filter('translate')('A10.list_head.column5'),
                    $scope.dispatched_show_label.LotNo = $filter('translate')('A10.list_head.column6'),
                    $scope.dispatched_show_label.Qty = $filter('translate')('A10.list_head.column7'),
                    $scope.dispatched_show_label.qty_not_in = $filter('translate')('A10.list_head.column17'),
                    $scope.dispatched_show_label.ProductNo = $filter('translate')('A10.list_head.column8'),
                    $scope.dispatched_show_label.ProductName = $filter('translate')('A10.list_head.column9'),
                    $scope.dispatched_show_label.ItemSpec = $filter('translate')('A10.list_head.column10'),
                    $scope.dispatched_show_label.CombinedTag = $filter('translate')('A10.list_head.column11'),
                    $scope.dispatched_show_label.StdDispStartTime = $filter('translate')('A10.list_head.column12'),
                    $scope.dispatched_show_label.StdDispEndTime = $filter('translate')('A10.list_head.column13'),
                    $scope.dispatched_show_label.DispStartTime = $filter('translate')('A10.list_head.column14'),
                    $scope.dispatched_show_label.DispEndTime = $filter('translate')('A10.list_head.column15'),
                    $scope.dispatched_show_label.monodate = $filter('translate')('A10.list_head.column16')
        };

        // 显示派工Tips
        $scope.showTips = function (item, e, i) {
            $scope.tempRow = item;
            e.preventDefault();
            e.stopPropagation();
            $scope.showTipsFlag = true;
            var popovertip = angular.element(document.getElementById('popover_id'));
            var index = document.getElementById('item' + i);
            popovertip.css('display', 'block');
            popovertip.css('top', $(index).offset().top + 5 + 'px');
            popovertip.css('left', $(index).offset().left + 'px');

        }
        // 隐藏派工Tips
        $scope.hideTips = function (item, e) {
            e.preventDefault();
            e.stopPropagation();
            $scope.showTipsFlag = false;
            $scope.tempRow = {};
        }

        // 显示待排Tips
        $scope.showDispatchTips = function (item, e, i) {
            $scope.dispatchedTempRow = item;
            e.preventDefault();
            e.stopPropagation();
            $scope.dispatchedShowTipsFlag = true;
            var popovertip = angular.element(document.getElementById('popover_id_wait'));
            var index = document.getElementById('item' + i);
            popovertip.css('display', 'block');
            popovertip.css('top', $(index).offset().top + 30 + 'px');
            popovertip.css('left', $(index).offset().left + 20 + 'px');

        }
        // 隐藏待排Tips
        $scope.hideDispatchTips = function (item, e) {
            e.preventDefault();
            e.stopPropagation();
            $scope.dispatchedShowTipsFlag = false;
            $scope.dispatchedTempRow = {};
        }

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.loadAreaInfo = function () {
            $MMWService.pageNumberInfoGet({
                page_mode: '54',
                query_condition_info: [
                    { column_name: 'A.MASTERNO', query_mode: '0', value: config.cache.account, merge_condition_model: 'AND' }
                ],
            }, function (itemList) {
                if (itemList.length != 0) {
                    $scope.area_detail = itemList;
                    if( $stateParams.data.selectareaNo) {
                        $scope.area_detail.forEach((item)=>{
                           if($stateParams.data.selectareaNo == item.page_no){
                             $scope.selectareaName =  item.page_no + ' (' + item.page_name + ')';
                           }
                          
                        });
                        $scope.selectareaNo = $stateParams.data.selectareaNo;
                    } else {
                        $scope.selectareaNo = $scope.area_detail[0].page_no;
                        $scope.selectareaName = $scope.area_detail[0].page_no + ' (' + $scope.area_detail[0].page_name + ')';

                    }
                    $scope.isLine = $scope.area_detail[0].area_type || '0';
                    $scope.selectWorkStation = '';
                  //  $scope.selectWorkStationName = '';
                    //step 2. 把第一筆區域當成預設值並帶入search 內查詢出資訊
                    //search({ return_type: '111' });
                    search2(1,function(){
                        search2(2);
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('A02.msg.noArea1'));
                }

            });
        }

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.loadMyFavorites = function () {
            $MMWService.showQueryListPNIG({
                page_mode: 53,
                mode: 'M',
                key: 'page_no',
                header: [
                    { label: $filter('translate')('common.queryList.area_c'), code: 'page_no' },
                    { label: $filter('translate')('common.queryList.area_n'), code: 'page_name' }
                ],
                selectKey: { key: 'isselect', true: '1', false: '0' },
                setCondition: function (conditions) {
                    conditions.push({ column_name: 'MASTERNO', query_mode: '0', value: config.cache.account, merge_condition_model: 'AND' });
                    return conditions;
                },
                confirm: function (selectItem, dialog) {
                    // 向数据库插入我的最爱数据信息
                    var content = {
                        master_no: config.cache.account, // 用户编号
                        master_type: 7,
                        favourite_user_area: []
                    };
                    selectItem.forEach(function (item) {
                        if (item.isselect == '1') {
                            content.favourite_user_area.push({ area_no: item.page_no });
                        }
                    });
                    if (content.favourite_user_area.length == 0) {
                        $scope.$root.showAlert($filter('translate')('A02.msg.lessThan'));
                    } else {
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                            content: content,
                            success: function (data) {
                                dialog.hide();
                                $scope.loadAreaInfo();
                            }
                        });
                    }
                }
            });
        };
        // 加载自定义排版
        $scope.loadSysSettings = function () {
            var resultList = [];
            resultList.push({ code: 'undsplist', label: $filter('translate')('customLayout.undsplistName') });
            resultList.push({ code: 'ondsplist', label: $filter('translate')('customLayout.ondsplistName') });
            $scope.showSelect({
                title: $filter('translate')('common.msg.plz_select'),
                label: 'label',
                code: 'code',
                list: resultList,
                confirm: function (item, d) {
                    d.hide();
                    let tempList = {};
                    var divId = '';
                    if (item.code == 'undsplist') {
                        divId = 'undsplist';
                        $scope.settingList.forEach(l => {
                            tempList[l] = null;
                        });
                    } else {
                        divId = 'ondsplist';
                        $scope.dispatchedSettingList.forEach(l => {
                            tempList[l] = null;
                        });
                    }

                    $mdDialog.serviceDialog('customerLayoutService', {
                        pageId: 'WIP007',
                        divId: divId,
                        styleFlag: false, // 是否控制行数限制
                        moreFlag: true,   // 是否显示更多排版页签
                        list: tempList,
                        callback: function () {
                            $state.reload();
                        }
                    });

                }
            });
        };

        $scope.back = function () {
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };
        $scope.orderbychange = function (mode) {
            //console.log($scope.order_by_mode);
            if ($scope.order_by_mode.name != mode) {
                $scope.order_by_mode.name = mode;
                $scope.order_by_mode.sort = false;
            }
            else {
                if ($scope.order_by_mode.sort)
                    $scope.order_by_mode.sort = false;
                else
                    $scope.order_by_mode.sort = true;
            }

        }
        //^_^ADD BY H-18036  20221201 FOR 新的查询方法
        function search2(type, feedback) {

            if ($scope.area_detail.length == 0) {
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function (dialog) {
                    dialog.hide();
                    $scope.loadMyFavorites();

                });
                return;
            }
            
            var content = {
                type: type,
                AreaNo: $scope.selectareaNo, 
                // 20230907 modify by wenwei for M# 144090 显示数据没有根据作业站显示
                lst_opno: $scope.op_group_detail.filter(item => item.is_select == 'true').map(item => item.op_no),
                Date_s: moment($scope.value_s).format('YYYY-MM-DD'),
                Date_e: moment($scope.value_e).format('YYYY-MM-DD'),
                EquipmentNo: $scope.assigned_machine,
                MoNo: $scope.assigned_wo_no,
                PlotNo: $scope.assigned_plot_no,
                is_urgent: $scope.do_flag, //0是1否
            }

            //当有设定已派工查询条件时，不可变更已派工顺序
            $scope.is_lock_sort = (content.MoNo == '' && content.PlotNo == '' && content.EquipmentNo == '');
            //if (content.MoNo == '' && content.PlotNo == '' && content.EquipmentNo == '') {
            //    $scope.is_lock_sort = false;
            //} else {
            //    $scope.is_lock_sort = true;
            //}

            if (($scope.assigned_wo_no == '' || $scope.assigned_wo_no == undefined) && ($scope.assigned_plot_no == '' || $scope.assigned_plot_no == undefined) && ($scope.assigned_machine == '' || $scope.assigned_machine == undefined) && $scope.do_flag == 1) {
                $scope.is_lock_sort = false;
            } else {
                $scope.is_lock_sort = true;
            }

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.adjust_dispatch_info_get',
                content: content,
                success: function (data) {
                      
                    if (data.QueryLotInfo && data.QueryLotInfo.length > 0)
                        $scope.QueryLotInfo = data.QueryLotInfo;
                    
                    else {
                        $scope.QueryLotInfo = []; //查无资料则刷新列表
                    }
                    dis_date_separate_action();//时间

                    if (sortablList) {
                        sortablList.destroy();
                        sortablList = undefined;
                        dispatched_detail_backup = undefined;
                        //$scope.QueryLotInfo = [];
                    }
                    //顺序调整初始加载-------------------------------start-----------------------------------------------
                    dispatched_detail_backup = $scope.QueryLotInfo.slice();
                    var list = [];
                    list = list.concat($scope.QueryLotInfo.filter(item => item.states != '0'));
                    list = list.concat($scope.QueryLotInfo.filter(item => item.states == '0'));
                    if (!$scope.is_lock_sort) {
                        $timeout(function () {
                            sortablList = Sortable.create(document.getElementById('sortablelist'), {
                                ghostClass: 'ghost',
                                filter: '.undragable',
                                handle: '.sortable-btn',
                                onEnd: function (evt) {
                                    if ($scope.Mode != 'EditSeq')
                                        $scope.Mode = 'EditSeq';
                                    ////console.log(evt);
                                    //if (item.dispatch_size === undefined) {
                                    //    item.dispatch_size = 0
                                    //}
                                    var dispatch_size = 0;
                                    var newIndex = evt.newIndex + dispatch_size;
                                    var oldIndex = evt.oldIndex + dispatch_size;
                                    var item = $scope.QueryLotInfo[oldIndex];
                                    //^_^ADD BY H-18036  20221214 FOR 调整顺序按钮 范围卡控----------------------------------------------------------
                                    var index_first = -1; //以日期+设备卡控调整范围的上坐标 该日期+设备第一次出现的位置
                                    var index_last = -1; //以日期+设备卡控调整范围的下坐标 该日期+设备最后一次出现的位置
                                    for(var i =0;i<$scope.QueryLotInfo.length;i++){
                                        if ($scope.QueryLotInfo[i].WORKDATE == item.WORKDATE && $scope.QueryLotInfo[i].EQUIPMENTNO == item.EQUIPMENTNO) {
                                            if (index_first == -1) {
                                                index_first = i; //第一笔数据出现的位置
                                            } else {
                                                index_last = i; //最后一笔数据出现的位置
                                            }
                                        }
                                    }
                                    var chooseItem = $scope.QueryLotInfo.splice(oldIndex, 1)[0];//删除原位置的数据并返回这条数据
                                    if (newIndex - index_first > 0 && index_last - newIndex>0) { //移动没有超出范围时
                                        newIndex = newIndex;
                                    } else if (newIndex - index_first<0) { //上移超出范围时
                                        newIndex = index_first;
                                    } else if (newIndex - index_last>0) { //下移超出范围时
                                        newIndex = index_last;
                                    }
                                    //-----------------------------------------------------------------------------------
                                    //20181218 add by Dustdusk for M#: 防止沒抓到還塞進陣列內
                                    if (chooseItem != undefined) {
                                        $scope.QueryLotInfo.splice(newIndex, 0, chooseItem);//将删除的数据插入新位置
                                        $scope.$apply();
                                    }
                                }
                                
                            });
                        });
                    } else {
                        $scope.$root.showToast($filter('translate')('A02.msg.cant_sort'));
                    }
                    //顺序调整初始加载-------------------------------end-----------------------------------------------

                    //^_^ADD BY H-18036  20221202 FOR 作业站相关处理 -------------------------
                    if (data.op_group_detail && data.op_group_detail.length > 0) {
                        //M#95547 熱處理優化 爐量顯示
                        var op_has_ht = 0;  // 熱處理 作業站計數
                        $scope.selectWorkStationName = '';
                        $scope.op_group_detail = data.op_group_detail;
                        if ($scope.op_group_detail && $scope.op_group_detail.length > 0) {
                            //M#95547 熱處理優化 爐量顯示
                            var op_has_ht = 0;  // 熱處理 作業站計數
                          // 多日派工跳转到派工跳转，作业站参数处理
                        //    if($stateParams.data.hasOwnProperty('lst_opno')){
                        //         $stateParams.data.lst_opno.forEach(function (item) {
                        //                 if (item.is_select == 'true')
                        //                     $scope.selectWorkStationName += item.op_name + ' \\ ';
                        //                     $scope.op_group_detail.push(item.op_no);
                        //                 if (item.plugin == 1) // plugin == 1 == 熱處理 作業站
                        //                     op_has_ht++;
                        //             });
                         //  } else {
                                $scope.op_group_detail.forEach(function (item) {
                                        if (item.is_select == 'true')
                                            $scope.selectWorkStationName += item.op_name + ' \\ ';
                                        if (item.plugin == 1) // plugin == 1 == 熱處理 作業站
                                            op_has_ht++;
                                    });
                          // }
                           
                            //判斷是否有熱處理作業站  大於 0 顯示爐量 
                            if (op_has_ht > 0)
                                $scope.ht_tr_bool = true;
                            else
                                $scope.ht_tr_bool = false;
                            $scope.selectWorkStationName = $scope.selectWorkStationName.substr(0, $scope.selectWorkStationName.length - 3);
                        }
                    }
                    //--------------------------------------------------------------
                    if (feedback)
                        feedback();
                }
            });

        }
        //---------------------------------------------------------
        function search(content, feedback) {

            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            if ($scope.area_detail.length == 0) {
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function (dialog) {
                    dialog.hide();
                    $scope.loadMyFavorites();

                });
                return;
            }

            //未派工
            //content.dispatch_detail_condition = [{
            //    wo_no: $scope.unassigned_wo_no || '',
            //    plot_no: $scope.unassigned_plot_no || ''
            //}];
            //已派工
            content.machine_detail_condition = [{
                wo_no: $scope.assigned_wo_no || '',
                plot_no: $scope.assigned_plot_no || ''
            }];
            //當有設定已派工查詢條件時，不可變更已派工順序
            if (content.machine_detail_condition[0].wo_no == '' && content.machine_detail_condition[0].plot_no == '') {
                $scope.is_lock_sort = false;
            } else {
                $scope.is_lock_sort = true;
            }
            content.op_no = '';
            content.area_no = $scope.selectareaNo;
            content.work_date = moment($scope.work_date).format('YYYY-MM-DD');

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content: content,
                success: function (data) {
                    var errorMsg = '';
                    //產品資料
                    if (data.product_detail && data.product_detail.length > 0)
                        $scope.product_detail = data.product_detail;
                    //已派工
                    if (content.return_type.charAt(1) == '1') {

                        // 20200319 modify by WeiTing for M#62127 - 增加過濾已派工的設備編號或設備名稱。
                        if ($scope.assigned_machine == '') {
                            $scope.machine_detail = data.machine_detail;
                        } else {
                            var machine_detail_filter = [];
                            data.machine_detail.forEach(function (item) {
                                if (item.machine_no.indexOf($scope.assigned_machine) != -1
                                || item.machine_name.indexOf($scope.assigned_machine) != -1) {
                                    machine_detail_filter.push(item);
                                }
                            });
                            $scope.machine_detail = machine_detail_filter;
                        };

                        if ($scope.machine_detail.length == 0) {
                            if (content.machine_detail_condition[0].wo_no == ''
                                && content.machine_detail_condition[0].plot_no == '') {
                                errorMsg += $filter('translate')('A02.msg.A01first') + '<br>';
                            } else {
                                errorMsg += $filter('translate')('common.msg.no_data') + '<br>';
                            }
                            $scope.pageInfo.totlePage = 1;
                        } else {
                            //算出機台總筆數
                            $scope.pageInfo.totlePage = Math.ceil($scope.machine_detail.length / $scope.pageInfo.perPageRow);
                        }
                    }

                    if (content.return_type.charAt(2) == '1') {
                        //M#95547 熱處理優化 爐量顯示
                        var op_has_ht = 0;  // 熱處理 作業站計數
                        $scope.selectWorkStationName = '';
                        $scope.op_group_detail = data.op_group_detail;
                        if ($scope.op_group_detail && $scope.op_group_detail.length > 0) {
                            //M#95547 熱處理優化 爐量顯示
                            var op_has_ht = 0;  // 熱處理 作業站計數
                            // 多日派工调整到派工调整作业站带入判断
                            $scope.op_group_detail.forEach(function (item) {
                                if (item.is_select == 'true')
                                    $scope.selectWorkStationName += item.op_name + ' \\ ';
                                if (item.plugin == 1) // plugin == 1 == 熱處理 作業站
                                    op_has_ht++;
                           });
                           
                            //判斷是否有熱處理作業站  大於 0 顯示爐量 
                            if (op_has_ht > 0)
                                $scope.ht_tr_bool = true;
                            else
                                $scope.ht_tr_bool = false;
                            $scope.selectWorkStationName = $scope.selectWorkStationName.substr(0, $scope.selectWorkStationName.length - 3);
                        }
                    }

                    if (errorMsg != '') {
                        $scope.$root.showAlert(errorMsg);
                    }

                    if (feedback)
                        feedback();

                    EquipmentSortAction();
                }
            });
        }

        //已派工查詢
        $scope.assigned_search = function () {
            //if ($scope.Mode == 'MachineExpend') {
            //    initMachineExpend($scope.selectMachine);
            //} else {
            //    search({ return_type: '010' });
            //}
            //search({ return_type: '010' });

            //检验起迄日期范围是否超过3个月
            var time = parseInt($scope.value_e - $scope.value_s) / 86400000;
            if (time > 90) {
                $scope.$root.showConfirm($filter('translate')('A10.msg.msg3'), function (dialog) {
                    dialog.hide();
                    search2(2);
                });
            } else {
                search2(2);
            }
            
        };

        //清除已派工查詢
        $scope.assigned_clear = function () {
            $scope.assigned_wo_no = '';
            $scope.assigned_plot_no = '';
            $scope.assigned_machine = '';
            $scope.do_flag = 1;
            $scope.assigned_search();
        };
        var dis_date_separate_action = function () {
            if ($scope.QueryLotInfo && $scope.QueryLotInfo.length > 0) {
                $scope.QueryLotInfo.forEach(function (item) {
                    if (item.DispStartTime && item.DispStartTime != "") {
                        var str_list = item.DispStartTime.split(" ");
                        if (str_list.length >= 2) {
                            item.dis_start_date = str_list[0];
                            item.dis_start_time = str_list[1];
                        }
                    }
                    else {
                        item.dis_start_date = moment($scope.work_date).format('YYYY-MM-DD');
                        item.dis_start_time = "00:00:00";
                    }
                    if (item.DispEndTime && item.DispEndTime != "") {
                        var str_list = item.DispEndTime.split(" ");
                        if (str_list.length >= 2) {
                            item.dis_end_date = str_list[0];
                            item.dis_end_time = str_list[1];
                        }
                    }
                    else {
                        item.dis_end_date = moment($scope.work_date).format('YYYY-MM-DD');
                        item.dis_end_time = "00:00:00";
                    }
                });
            }
        }

        $scope.time_open_set = function (event, detail, time, type) {
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            var rule = /^\d{2}:\d{2}:\d{2}$/;
            if (rule.test(time) == false)
                time = "00:00:00";
            $calculater.open(function (timeDisplay, dialog) {
                angular.element(target).removeClass('is-focus');
                var hour = timeDisplay.hour, min = timeDisplay.minute, sec = timeDisplay.second;

                var time_str = hour + ":" + min + ":" + sec;
                if ((0 <= (+hour) && (+hour) < 24) &&
                (0 <= (+min) && (+min) < 60) &&
                (0 <= (+sec) && (+sec) < 60) && rule.test(time_str)) {
                    var content = {};
                    var time_check = true;
                    content.need_dispatch_plot_detail = [];
                    if (type == 4) {
                        detail.dis_start_time = time_str;
                        detail.dis_time = detail.dis_start_date + " " + time_str;
                        content.work_mode = "4";
                    }
                    else if (type == 5) {
                        detail.dis_time = detail.dis_end_date + " " + time_str;
                        content.work_mode = "5";
                        if (Date.parse(detail.dis_plot_start_time) > Date.parse(detail.dis_time))
                            time_check = false;
                        if (time_check)
                            detail.dis_end_time = time_str;
                    }
                    if (time_check) {
                        content.need_dispatch_plot_detail.push({
                            plot_no: detail.LotNo,
                            op_no: detail.OPNO,
                            qty: detail.Qty,
                            mo_no: detail.MONO,
                            machine_no: detail.EQUIPMENTNO,
                            plot_start_time: detail.StdDispStartTime,
                            plot_end_time: detail.StdDispEndTime,
                            dis_time: detail.dis_time
                        });
                        content.dispatch_to = [];
                        content.with_draw_mode = "0";
                        //content.dispatch_day = moment($scope.work_date).format('YYYY-MM-DD');
                        content.dispatch_day = moment(detail.WORKDATE).format('YYYY-MM-DD');
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                            content: content,
                            success: function (data) {
                                search2(2, function () {
                                    $scope.$root.showToast($filter('translate')('A05.js.success'));
                                    $scope.Mode = '';
                                    //var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                    //if (machine != undefined && machine.length > 0) {
                                    //    $scope.selectMachine = machine[0];
                                    //}
                                    //initMachineExpend($scope.selectMachine);
                                });
                            }
                        });
                    }
                    else
                        $scope.$root.showAlert($filter('translate')('A02.alert.time_error_msg'));
                    //console.log(content);

                    angular.element(target).removeClass('is-focus');
                    dialog.hide();
                } else {
                    if ($scope.$root.showAlert)
                        $scope.$root.showAlert($filter('translate')('common.msg.time_format_error'));
                }
            },
            function (dialog) {
                angular.element(target).removeClass('is-focus');
                dialog.hide();
            },
    	    {
    	        type: "date",
    	        defaultNum: time,
    	        title: $filter('translate')('common.msg.select_time'),
    	        decimal: false
    	    });
        };
        //dis_date_separate_action = function () {
        //    if ($scope.QueryLotInfo && $scope.QueryLotInfo.length > 0) {
        //        $scope.QueryLotInfo.forEach(function (item) {
        //            if (item.DispStartTime && item.DispStartTime != "") {
        //                var str_list = item.DispStartTime.split(" ");
        //                if (str_list.length >= 2) {
        //                    item.dis_start_date = str_list[0];
        //                    item.dis_start_time = str_list[1];
        //                }
        //            }
        //            else {
        //                item.dis_start_date = moment($scope.work_date).format('YYYY-MM-DD');
        //                item.dis_start_time = "00:00:00";
        //            }
        //            if (item.DispEndTime && item.DispEndTime != "") {
        //                var str_list = item.DispEndTime.split(" ");
        //                if (str_list.length >= 2) {
        //                    item.disp_end_date = str_list[0];
        //                    item.disp_end_time = str_list[1];
        //                }
        //            }
        //            else {
        //                item.disp_end_date = moment($scope.work_date).format('YYYY-MM-DD');
        //                item.disp_end_time = "00:00:00";
        //            }
        //        });
        //    }
        //}
        //$scope.time_open_set = function (event, detail, time, type) {
        //    var target = event.currentTarget;
        //    angular.element(target).addClass('is-focus');
        //    var rule = /^\d{2}:\d{2}:\d{2}$/;
        //    if (rule.test(time) == false)
        //        time = "00:00:00";
        //    $calculater.open(function (timeDisplay, dialog) {
        //        angular.element(target).removeClass('is-focus');
        //        var hour = timeDisplay.hour, min = timeDisplay.minute, sec = timeDisplay.second;

        //        var time_str = hour + ":" + min + ":" + sec;
        //        if ((0 <= (+hour) && (+hour) < 24) &&
        //        (0 <= (+min) && (+min) < 60) &&
        //        (0 <= (+sec) && (+sec) < 60) && rule.test(time_str)) {
        //            var content = {};
        //            var time_check = true;
        //            content.need_dispatch_plot_detail = [];
        //            if (type == 4) {
        //                detail.dis_start_time = time_str;
        //                detail.dis_time = detail.dis_start_date + " " + time_str;
        //                content.work_mode = "4";
        //            }
        //            else if (type == 5) {
        //                detail.dis_time = detail.disp_end_date + " " + time_str;
        //                content.work_mode = "5";
        //                if (Date.parse(detail.dis_plot_start_time) > Date.parse(detail.dis_time))
        //                    time_check = false;
        //                if (time_check)
        //                    detail.disp_end_time = time_str;
        //            }
        //            if (time_check) {
        //                content.need_dispatch_plot_detail.push({
        //                    plot_no: detail.plot_no,
        //                    op_no: detail.op_no,
        //                    qty: detail.plot_qty,
        //                    mo_no: detail.mo_no,
        //                    //machine_no: $scope.selectMachine.machine_no,
        //                    plot_start_time: detail.plot_start_time,
        //                    plot_end_time: detail.plot_end_time,
        //                    dis_time: detail.dis_time
        //                });
        //                content.dispatch_to = [];
        //                content.with_draw_mode = "0";
        //                content.dispatch_day = moment($scope.work_date).format('YYYY-MM-DD');
        //                $MMWService.sendToServer({
        //                    uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
        //                    content: content,
        //                    success: function (data) {
        //                        search({ return_type: '110' }, function () {
        //                            $scope.$root.showToast($filter('translate')('A05.js.success'));
        //                            $scope.Mode = 'MachineExpend';
        //                            var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
        //                            if (machine != undefined && machine.length > 0) {
        //                                $scope.selectMachine = machine[0];
        //                            }
        //                            initMachineExpend($scope.selectMachine);
        //                        });
        //                    }
        //                });
        //            }
        //            else
        //                $scope.$root.showAlert($filter('translate')('A02.alert.time_error_msg'));
        //            //console.log(content);

        //            angular.element(target).removeClass('is-focus');
        //            dialog.hide();
        //        } else {
        //            if ($scope.$root.showAlert)
        //                $scope.$root.showAlert($filter('translate')('common.msg.time_format_error'));
        //        }
        //    },
        //    function (dialog) {
        //        angular.element(target).removeClass('is-focus');
        //        dialog.hide();
        //    },
    	//    {
    	//        type: "date",
    	//        defaultNum: time,
    	//        title: $filter('translate')('common.msg.select_time'),
    	//        decimal: false
    	//    });
        //};
        //選擇區域
        $scope.loadAreaList = function () {
            
             // 20230922 modify by shiwl: 厦晖：多日派工的时候，点击设备跳到派工调整，派工调整这边作业选择切换区域后设备信息没有自动清楚
             $scope.assigned_machine = "";
             $scope.assigned_wo_no = "";
             $scope.assigned_plot_no = "";

            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            if ($scope.area_detail.length == 0) {
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function (dialog) {
                    dialog.hide();
                    $scope.loadMyFavorites();

                });
                return;
            }

            $scope.$root.showQueryList({
                key: 'page_no',
                header: [
                    { label: $filter('translate')('common.queryList.area_c'), code: 'page_no' },
                    { label: $filter('translate')('common.queryList.area_n'), code: 'page_name' }
                ],
                query: function (conditions, feedback) {
                    feedback($scope.area_detail);
                },
                selectCode: $scope.selectareaNo || '',
                confirm: function (selectItem, dialog) {
                    $scope.selectareaNo = selectItem.page_no;
                    $scope.selectareaName = selectItem.page_no + ' (' + selectItem.page_name + ')';
                    $scope.isLine = selectItem.area_type || '0';
                    dialog.hide();
                    //查出全部資料
                    //search({ return_type: '111' });
                    search2(1);
                }
            });
        };

        //選擇作業站
        $scope.loadWorkStationList = function () {
            var content = {};
            content.area_no = $scope.selectareaNo;
            content.return_type = "001";
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content: content,
                success: function (data) {
                    if (data && data.op_group_detail) {
                        $scope.op_group_detail = data.op_group_detail
                    }
                    $scope.$root.showQueryList({
                        mode: 'M',
                        key: 'op_no',
                        header: [
                            { label: $filter('translate')('common.queryList.op_c'), code: 'op_no' },
                            { label: $filter('translate')('common.queryList.op_n'), code: 'op_name' }
                        ],
                        query: function (conditions, feedback) {
                            feedback($scope.op_group_detail);
                        },
                        selectKey: { key: 'is_select', true: 'true', false: 'false' },
                        confirm: function (selectItem, dialog) {
                            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                            var content = {
                                master_no: $scope.selectareaNo,
                                master_type: 8,
                                favourite_user_opno: [],
                                user_no: config.cache.account // 用户编号
                            },
                            selectWorkStationName = '';
                            selectItem.forEach(function (item) {
                                if (item.is_select == 'true') {
                                    // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                    content.favourite_user_opno.push({ op_no: item.op_no });

                                    selectWorkStationName += item.op_name + ' \\ ';
                                }
                            });
                            selectWorkStationName = selectWorkStationName.substr(-3, 3);

                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                content: content,
                                success: function (data) {
                                    $scope.selectWorkStation = '';
                                    $scope.selectWorkStationName = selectWorkStationName;
                                    dialog.hide();
                                    //search({ return_type: '111' });
                                    search2(1);
                                }
                            });
                        }
                    });
                }
            });
        };

        $scope.changeDate = function () {
            $datePicker.open($scope.work_date,
            function (dialog) {
                $scope.work_date = dialog.datePacker.pickDate;
                dialog.hide();
                search({ return_type: '010' }, function () {
                    if ($scope.Mode == 'MachineExpend') {
                        initMachineExpend($scope.selectMachine);
                    }
                });
            },
            function (dialog) {
                dialog.hide();
            }, {});
        };

        $scope.prevDate = function () {
            $scope.work_date = moment($scope.work_date).add(-1, 'd').toDate();
            search({ return_type: '010' }, function () {
                if ($scope.Mode == 'MachineExpend') {
                    initMachineExpend($scope.selectMachine);
                }
            });
        };

        $scope.nextDate = function () {
            $scope.work_date = moment($scope.work_date).add(1, 'd').toDate();
            search({ return_type: '010' }, function () {
                if ($scope.Mode == 'MachineExpend') {
                    initMachineExpend($scope.selectMachine);
                }
            });
        };

        var selectWorkItemCount = 0;
        $scope.itemSelect = function (index, work) {
            if (work.status == '0') {
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
            }
            if (work.checked == 'Y') {
                work.checked = undefined;
                selectWorkItemCount--;
            } else if (!work.checked) {
                work.checked = 'Y';
                selectWorkItemCount++;
            }

            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            if (selectWorkItemCount == 0) {
                $scope.Mode = '';
                $scope.showMode = 'query';
            } else {
                $scope.Mode = 'EditSendWork';
                $scope.showMode = 'preview'
            }

            EquipmentSortAction();
        };
        $scope.itemAllAction = function () {
            if ($scope.dispatch_detail.length <= 0)
                return;
            for (var i in $scope.dispatch_detail) {
                if ($scope.select_all_bool)
                    $scope.dispatch_detail[i].checked = '';
                else {
                    // 狀態 0 代表任務在智派工納入派工，不可勾選！
                    if ($scope.dispatch_detail[i].status == '0')
                        $scope.dispatch_detail[i].checked = '';
                    else
                        $scope.dispatch_detail[i].checked = 'Y';
                }
            }

            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            if ($scope.select_all_bool) {
                $scope.showMode = "query"
                $scope.select_all_bool = false;
                $scope.Mode = '';
                selectWorkItemCount = 0;
            }
            else {
                $scope.showMode = "preview"
                $scope.select_all_bool = true;
                $scope.Mode = 'EditSendWork';
                selectWorkItemCount = $scope.dispatch_detail.length;
            }
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        var pdf_url;
        $scope.preview = function () {
            var plot_detail = [];
            if ($scope.Mode == 'Rollback') {
                $scope.QueryLotInfo.forEach(function (item) {
                    if (item.checked == 'Y') {
                        var info = {
                            plot_no: item.LotNo,
                            plot_qty: item.Qty
                        }
                        plot_detail.push(info);
                    }
                });
            } else {
                var QueryLotInfo = $filter('filter')($scope.dispatch_detail, $scope.dispatch_filter);
                QueryLotInfo.forEach(function (detail, index) {
                    if (detail.checked == 'Y') {
                        var info = {
                            plot_no: detail.LotNo,
                            plot_qty: detail.Qty
                        }
                        plot_detail.push(info);
                    }
                });
            }

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.runcard_pdf_get',
                content: {
                    course: ($scope.show_history ? '1' : '0'),
                    plot_detail: plot_detail
                },
                success: function (data) {

                    for (var i = 0; i < plot_detail.length; i++) {
                        $scope.printList.push({
                            printNo: plot_detail[i].plot_no,
                            printType: '1' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                        });
                    }

                    pdf_url = data.runcard_pdf_get[0].url_pdf;
                    if (pdf_url.indexOf('http://') == -1) {
                        pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                    }
                    if (config.setting.outsidePDF == 'Y') {
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try {
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        } catch (e) {
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if (!fs.existsSync(RuncardPath)) {
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })

                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                            const { shell } = window.nodeRequire('electron');
                            shell.openItem ? shell.openItem(dist_path) : shell.openPath(dist_path);
                        });
                    } else {
                        showPDFViewer(pdf_url);
                    }
                }
            });
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        function showPDFViewer(pdf_url) {
            try {
                window.nodeRequire('nw.gui').Window.open(pdf_url, {
                    title: 'PDF Viewer',
                    show: false,
                    icon: 'icon/icon.png',
                    focus: true
                }, function (win) {
                    win.on('loaded', function () {
                        win.show();
                        win.print();
                    });
                });
            } catch (e) {
                $scope.showMode = 'print';
                document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file=' + pdf_url + '&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
            }
        }

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.print = function () {
            if (window.nodeRequire) {
                var sumatraPDF = window.nodeRequire('sumatra-pdf');
                if (sumatraPDF) {
                    var fs = window.nodeRequire('fs'), RuncardPath;
                    try {
                        // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                        const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                        RuncardPath = remote.app.getAppPath();
                    } catch (e) {
                        RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                    }
                    RuncardPath += '\\www\\Runcard';
                    if (!fs.existsSync(RuncardPath)) {
                        fs.mkdirSync(RuncardPath);
                    }

                    // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                    // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                    fs.readdirSync(RuncardPath, (err, files) => {
                        if (err) {
                            console.log(err);
                        }
                        //listing all files using forEach
                        files.forEach((file) => {
                            // Do whatever you want to do with the file
                            fs.unlink(RuncardPath + '/' + file, (err) => {
                                if (err) {
                                    console.debug(err);
                                }
                            })
                        });
                    })

                    // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                    let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                    $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                        $scope.$root.showLoading();
                        window.nodeRequire('sumatra-pdf').printWithSettings({
                            path: dist_path,
                            success: function () {
                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                            },
                            error: function (error) {
                                // 20201104 modify by WeiTing for M#77013 - 不清楚為何在實際列印後，有列印成一張紙或輸出成 PDF檔案時，都會執行 error區域，所以目前 error區域也先當列印完成後，把列印詳情回送給後台做記錄。
                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                                //console.error(error);
                            }
                        });
                    });
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
            /*
            if(config.setting.printSetting){
                $PrintSetting.init({
                    callback:function(settings){
                        window.frames['kmi-pdf-panel'].pdf_print(settings);
                    }
                });
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
            */
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.download = function () {
            window.frames['kmi-pdf-panel'].pdf_download();
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.cancel = function () {
            if ($scope.Mode == 'Rollback') {
                $scope.showMode = 'query';
            } else {
                $scope.showMode = 'preview';
            }
            document.getElementById('kmi-pdf-panel').src = '';
            $scope.printList = [];
        };

        // 20201216 ADD FOR M#83236-1
        // 列印完成後，需把列印詳情回送給後台做記錄
        function printWiplogProcess() {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.print_wiplog_process',
                content: {
                    printList: $scope.printList
                },
                success: function () {
                    $scope.printList = [];
                }
            });
        }

        $scope.pageInfo = {
            nowPage: 1,
            totlePage: 1,
            perPage: 10,
            perPageRow: 5
        };

        $scope.machineStatus = function (status) {
            return 'status_' + status;
        };

        $scope.selectMachine = undefined;
        $scope.getMachineList = function () {
            var start = ($scope.pageInfo.nowPage - 1) * $scope.pageInfo.perPageRow;
            var end = ($scope.pageInfo.nowPage) * $scope.pageInfo.perPageRow;
            return $scope.machine_detail.slice(start, end);
        };

        $scope.prevPage = function () {
            if ($scope.pageInfo.nowPage > 1)
                $scope.pageInfo.nowPage--;
        };

        $scope.nextPage = function () {
            if ($scope.pageInfo.nowPage < $scope.pageInfo.totlePage)
                $scope.pageInfo.nowPage++;
        };

        //展開機台上的已派工清單
        //尝试注释2
        //function expendMachine(index, item, event) {

        //    if ($scope.Mode != 'MachineExpend') {
        //        $scope.Mode = 'MachineExpend';
        //        $scope.selectMachine = item;
        //        $scope.selectMachine.dispatch_size = 0;
        //        initMachineExpend($scope.selectMachine);
        //    } else if (selectWorkItemCount != 0) {
        //        $scope.Mode = 'EditSendWork';
        //        $scope.selectMachine = undefined;
        //    }
        //    event.preventDefault();
        //}

        var sortablList, dispatched_detail_backup;
        //尝试注释3
        //function initMachineExpend(item) {
        //    // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        //    if ($scope.area_detail.length == 0) {
        //        var msg = $filter('translate')('A02.alert.msg2');
        //        $scope.$root.showConfirm(msg, function (dialog) {
        //            dialog.hide();
        //            $scope.loadMyFavorites();

        //        });
        //        return;
        //    }

        //    var content = {
        //        area_no: $scope.selectareaNo,
        //        machine_no: item.machine_no,
        //        work_date: moment($scope.work_date).format('YYYY-MM-DD'),
        //        machine_detail_condition: [{
        //            wo_no: $scope.assigned_wo_no || '',
        //            plot_no: $scope.assigned_plot_no || ''
        //        }],
        //        return_type: '020'//已派工 20220314 modi by wangyq for M#107976 old:121
        //    };
        //    dispatch_info_get_machine_detail(content, function (dispatched_detail) {
        //        if (sortablList) {
        //            sortablList.destroy();
        //            sortablList = undefined;
        //            dispatched_detail_backup = undefined;
        //            $scope.dispatched_detail = [];
        //        }
        //        dispatched_detail_backup = dispatched_detail.slice();
        //        //20220929 modify by wangzy for 0119508: 华禹彩印：派工作业处部分已派工数据无法调整顺序
        //        var list = [];
        //        list = list.concat(dispatched_detail.filter(item => item.states != '0'));
        //        list = list.concat(dispatched_detail.filter(item => item.states == '0'));
        //        $scope.dispatched_detail = list;
        //        dis_date_separate_action();
        //        if (content.machine_detail_condition[0].wo_no == '' && content.machine_detail_condition[0].plot_no == '') {
        //            $scope.is_lock_sort = false;
        //        } else {
        //            $scope.is_lock_sort = true;
        //        }

        //        if (!$scope.is_lock_sort) {
        //            $timeout(function () {
        //                sortablList = Sortable.create(document.getElementById('sortablelist'), {
        //                    ghostClass: 'ghost',
        //                    filter: '.undragable',
        //                    handle: '.sortable-btn',
        //                    onEnd: function (evt) {
        //                        if ($scope.Mode != 'EditSeq')
        //                            $scope.Mode = 'EditSeq';
        //                        //console.log(evt);
        //                        if (item.dispatch_size === undefined) {
        //                            item.dispatch_size = 0
        //                        }
        //                        var newIndex = evt.newIndex + item.dispatch_size;
        //                        var oldIndex = evt.oldIndex + item.dispatch_size;
        //                        var chooseItem = $scope.dispatched_detail.splice(oldIndex, 1)[0];
        //                        //20181218 add by Dustdusk for M#: 防止沒抓到還塞進陣列內
        //                        if (chooseItem != undefined) {
        //                            $scope.dispatched_detail.splice(newIndex, 0, chooseItem);
        //                            $scope.$apply();
        //                        }
        //                    }
        //                });
        //            });
        //        } else {
        //            $scope.$root.showToast($filter('translate')('A02.msg.cant_sort'));
        //        }
        //    });
        //}

        var MachineListMode = '', dispatchItem, machineList;
        $scope.itemSendwork = function (index, item) {
            if (item.status == '0') {
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
            }
            if ($scope.Mode != 'EditSendWork') {
                var feedback = function (data) {
                    MachineListMode = '1';//表示派工
                    dispatchItem = item;
                    machineList = EquipmentSortForDialogAction(item, data);
                    $mdDialog.dialog(
                            'module/moduleA/program/A02/A2_MachineList.tmp.html',
                            MachineListController
                    );
                };
                if ($scope.isLine == '1')
                    getLineMachineList(item.plot_no, item.op_no, $scope.work_date, feedback);
                else
                    getMachineList($scope.work_date, feedback);
            }
        };

        $scope.itemAccessory = function (item) {
            $scope.acc_detail = [];
            if (!item.accessory_no) {
                $scope.$root.showAlert($filter('translate')('A02.msg.no_accessory_no'));
                return;
            }
            $scope.acc_detail = item.product_acc_detail;
            $mdDialog.dialog(
                'module/moduleA/program/A02/A2_AccList.tmp.html',
                AccDetailController
            );
        };

        function AccDetailController(dialog) {
            return {
                product_acc_detail: $scope.acc_detail,
                PageConfig: { page: 0, page_count: 25 },
                order_by_mode: { name: "", sort: false },
                dispatch_filter: {},
                orderbychange: function (mode) {
                    if (dialog.order_by_mode.name != mode) {
                        dialog.order_by_mode.name = mode;
                        dialog.order_by_mode.sort = false;
                    }
                    else {
                        if (dialog.order_by_mode.sort)
                            dialog.order_by_mode.sort = false;
                        else
                            dialog.order_by_mode.sort = true;
                    }

                },
                getPages: function (list, PageConfig, filterItem) {
                    if (list) {
                        if (dialog.order_by_mode.name != "")
                            list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                    if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        if (PageConfig) {
                            if (temp_list.length != 0) {
                                PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                                if (PageConfig.page >= PageConfig.total_page) {
                                    PageConfig.page = 0;
                                }
                                var index = PageConfig.page * PageConfig.page_count;
                                return temp_list.slice(index, index + PageConfig.page_count);
                            } else {
                                PageConfig.total_page = 1;
                                PageConfig.page = 0;
                            }
                        } else {
                            return temp_list;
                        }
                    } else {

                        return list;
                    }
                },
                back: function () {
                    dialog.hide();
                }
            }
        }

        //改派----Controller
        function MachineListController(dialog) {
            return {
                Qty_show: (dispatchItem.Qty < dispatchItem.qty) ? dispatchItem.Qty : dispatchItem.qty, //Qty 当日派工数量 qty总未进站数量
                isLine: $scope.isLine,
                MachineListMode: MachineListMode,
                //work_date: $scope.work_date,
                work_date: moment($scope.value_e).format('YYYY-MM-DD'),// 20230809 modify  by shiwl for 0142522: [MSSQL][6.0][在线][派工调度中心]派工调整，选中任务点击改派，改派界面的派工日期默认为派工调整界面的派工日期迄
                dispatchItem: dispatchItem,
                machineList: machineList,
                mlightColor: $scope.mlightColor,
                order_by_mode: { name: "", sort: false },
                dispatch_filter: {},
                orderbychange: function (mode) {
                    if (dialog.order_by_mode.name != mode) {
                        dialog.order_by_mode.name = mode;
                        dialog.order_by_mode.sort = false;
                    }
                    else {
                        if (dialog.order_by_mode.sort)
                            dialog.order_by_mode.sort = false;
                        else
                            dialog.order_by_mode.sort = true;
                    }

                },
                getMachineList: function (list, filterItem) {
                    if (list) {
                        if (dialog.order_by_mode.name != "")
                            list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                    if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        return temp_list;
                    } else {
                        return list;
                    }
                },
                changeDate: function () {
                    $datePicker.open(dialog.work_date,
                    function (mdDialog) {
                        dialog.work_date = mdDialog.datePacker.pickDate;
                        mdDialog.hide();
                        var feedback = function (data) {
                            dialog.machineList = data;
                        };
                        if ($scope.isLine == '1')
                            getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                        else
                            getMachineList(dialog.work_date, feedback);
                    },
                    function (dialog) {
                        dialog.hide();
                    }, {});
                },
                prevDate: function () {
                    dialog.work_date = moment(dialog.work_date).add(-1, 'd').toDate();
                    var feedback = function (data) {
                        dialog.machineList = data;
                    };
                    if ($scope.isLine == '1')
                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                    else
                        getMachineList(dialog.work_date, feedback);
                },
                nextDate: function () {
                    dialog.work_date = moment(dialog.work_date).add(1, 'd').toDate();
                    var feedback = function (data) {
                        dialog.machineList = data;
                    };
                    if ($scope.isLine == '1')
                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                    else
                        getMachineList(dialog.work_date, feedback);
                },
                back: function () {
                    dialog.hide();
                },
                confirm: function () {
                    if (MachineListMode == '1') { //派工
                        MachineListConfirmDispatch(dialog);
                    } else if (MachineListMode == '2') { //改派
                        MachineListConfirmTransfer(dialog);
                    }
                    $scope.roll_back_all_bool = false;
                }
            };
        }

        function getMachineList(work_date, feedback) {
            var content = {
                dispatch_detail_condition: [{ wo_no: '', plot_no: '' }],//未派工
                machine_detail_condition: [{ wo_no: '', plot_no: '' }],//已派工
                op_no: '',
                area_no: $scope.selectareaNo,
                work_date: moment(work_date).format('YYYY-MM-DD'),
                return_type: '010'
            };

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content: content,
                success: function (data) {
                    //已派工
                    if (data.machine_detail && data.machine_detail.length != 0) {
                        if (feedback)
                            feedback(data.machine_detail);
                    } else {
                        $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                    }
                }
            });
        }

        function getLineMachineList(plot_no, op_no, work_date, feedback) {
            var content = {
                page_mode: 'dispatch_line_equipment_info_get',
                query_condition_info: []
            };
            content.query_condition_info.push({ column_name: 'A.LOTNO', query_mode: '0', value: plot_no, merge_condition_model: 'AND' });
            content.query_condition_info.push({ column_name: 'A.OPNO', query_mode: '0', value: op_no, merge_condition_model: 'AND' });
            content.query_condition_info.push({ column_name: 'workdate', query_mode: '0', value: moment(work_date).format('YYYYMMDD') + '000000', merge_condition_model: 'AND' });

            $MMWService.pageNumberInfoGet(content, function (data) {
                //已派工
                if (data && data.length != 0) {
                    data.forEach(function (machine) {
                        machine.used_capacity = Math.round(machine._used_capacity * 100 / 60) / 100;
                        machine.machine_load = Math.round(machine.used_capacity * 100 / machine.capacity);
                        if (machine.machine_load > 80)
                            machine.load_status = 'H';
                        else if (machine.machine_load >= 60)
                            machine.load_status = 'M';
                        else
                            machine.load_status = 'L';
                    });
                    if (feedback)
                        feedback(data);
                } else {
                    $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                }
            });
        }

        //派工到多機台
        //function MachineListConfirmDispatch(dialog) {
        //    var dispatchSum = 0;
        //    var content = {
        //        need_dispatch_plot_detail: [dispatchItem],
        //        dispatch_to: [],
        //        work_mode: 1,
        //        dispatch_day: moment(dialog.work_date).format('YYYY-MM-DD')
        //    };

        //    dialog.machineList.forEach(function (machine, index) {
        //        if (machine.inputQty != undefined && machine.inputQty != 0) {
        //            content.dispatch_to.push({ machine_no: machine.machine_no, qty: machine.inputQty });
        //            dispatchSum += (+machine.inputQty);
        //        }
        //    });

        //    var _fn = function (request) {
        //        $MMWService.sendToServer({
        //            uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
        //            content: request,
        //            success: function (data) {
        //                if (data.dispatch_msg && data.dispatch_msg.length > 0) {
        //                    var msg = data.dispatch_msg.join("<br>")
        //                    $scope.$root.showConfirm(msg, function (confirm_dialog) {
        //                        confirm_dialog.hide();
        //                        enforce_dispatch_action(request, function () {
        //                            dialog.hide();
        //                            $scope.work_date = dialog.work_date;
        //                            search({ return_type: '110' }, function () {
        //                                $scope.$root.showToast(dispatchItem.plot_no + $filter('translate')('A02.msg.saveSuccess'));
        //                            });
        //                        });
        //                    });
        //                }
        //                else {
        //                    dialog.hide();
        //                    $scope.work_date = dialog.work_date;
        //                    search({ return_type: '110' }, function () {
        //                        $scope.$root.showToast(dispatchItem.plot_no + $filter('translate')('A02.msg.saveSuccess'));
        //                    });
        //                }
        //            }
        //        });
        //    };

        //    if (content.dispatch_to.length == 0) {
        //        //尚未輸入派工數量
        //        $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
        //    } else if (dispatchSum <= dispatchItem.qty) {
        //        dispatch_info_calculation_process(content, function (data) {
        //            if (data && data.suggest_detail && data.suggest_detail.length > 0) {
        //                OpenMachineSuggestListDialog(1, content, data.suggest_detail);
        //                dialog.hide();
        //            }
        //            else if (data && data.msg != '') {
        //                $scope.$root.showConfirm(data.msg, function (dialogType) {
        //                    dialogType.hide();
        //                    _fn(content);
        //                });
        //            }
        //            else {
        //                _fn(content);
        //            };
        //        });
        //    } else {
        //        $scope.$root.showAlert($filter('translate')('A02.msg.numOver') + dispatchItem.qty);
        //    }
        //}
        //尝试注释1
        //$scope.machineSelect = function (index, machine, event) {
        //    if ($scope.Mode == 'EditSendWork') {
        //        itemMutiSendwork(machine);
        //    } else {
        //        expendMachine(index, machine, event);
        //    }
        //};

        $scope.closeMachine = function () {
            $scope.Mode = '';
            $scope.selectMachine = undefined;
            if (sortablList) {
                sortablList.destroy();
                sortablList = undefined;
                dispatched_detail_backup = undefined;
                $scope.dispatched_detail = [];
            }
        };

        //多生產批同時派工
        //function itemMutiSendwork(machine) {
        //    var content = {
        //        need_dispatch_plot_detail: [],
        //        dispatch_to: [{ machine_no: machine.machine_no, }],
        //        work_mode: 1,
        //        dispatch_day: moment($scope.work_date).format('YYYY-MM-DD')
        //    };
        //    var filter_result = $filter('filter')($scope.dispatch_detail, $scope.dispatch_filter);
        //    filter_result.forEach(function (detail, index) {
        //        if (detail.checked == 'Y') {
        //            content.need_dispatch_plot_detail.push(detail);
        //        }
        //    });
        //    if (content.need_dispatch_plot_detail.length <= 0) {
        //        $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_detail'));
        //        return;
        //    }
        //    if (content.need_dispatch_plot_detail.length == 1) {
        //        content.dispatch_to[0].qty = content.need_dispatch_plot_detail[0].qty;
        //    }

        //    var _fn = function (request) {
        //        $MMWService.sendToServer({
        //            uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
        //            content: request,
        //            success: function (data) {
        //                if (data.dispatch_msg && data.dispatch_msg.length > 0) {
        //                    var msg = data.dispatch_msg.join("<br>")
        //                    $scope.$root.showConfirm(msg, function (confirm_dialog) {
        //                        confirm_dialog.hide();
        //                        enforce_dispatch_action(request, function () {
        //                            search({ return_type: '110' }, function () {
        //                                $scope.$root.showToast(
        //                                    content.need_dispatch_plot_detail.length
        //                                    + $filter('translate')('A02.msg.sendWorkSuccess')
        //                                    + '[' + machine.machine_no + ']');
        //                                $scope.Mode = '';
        //                                selectWorkItemCount = 0;
        //                                $scope.select_all_bool = false;
        //                                // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        //                                $scope.showMode = 'query';
        //                            });
        //                        });
        //                    });
        //                }
        //                else {
        //                    search({ return_type: '110' }, function () {
        //                        $scope.$root.showToast(
        //                            content.need_dispatch_plot_detail.length
        //                            + $filter('translate')('A02.msg.sendWorkSuccess')
        //                            + '[' + machine.machine_no + ']');
        //                        $scope.Mode = '';
        //                        selectWorkItemCount = 0;
        //                        $scope.select_all_bool = false;
        //                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        //                        $scope.showMode = 'query';
        //                    });
        //                }
        //            }
        //        });
        //    };

        //    dispatch_info_calculation_process(content, function (data) {
        //        if (data && data.suggest_detail && data.suggest_detail.length > 0) {
        //            OpenMachineSuggestListDialog(0, content, data.suggest_detail);
        //        }
        //        else if (data && data.msg != '') {
        //            $scope.$root.showConfirm(data.msg, function (dialogType) {
        //                dialogType.hide();
        //                _fn(content);
        //            });
        //        }
        //        else {
        //            _fn(content);
        //        };
        //    });
        //};
        //建议数量开窗
        //work_mode = 0 =多筆生產批派一筆設備 
        //work_mode = 1 = 一筆生產批派多個設備
        //submit_data = 派工原始明細
        //suggest_detail = 派工建議明細
        function OpenMachineSuggestListDialog(work_mode, submit_data, suggest_detail) {
            $mdDialog.dialog(
                'module/moduleA/program/A02/A2_MachineList_suggest.html',
                function (dialog) {
                    return {
                        suggest_detail: suggest_detail,
                        mlightColor: $scope.mlightColor,
                        submit_data: submit_data,
                        work_mode: work_mode,
                        order_by_mode: { name: "", sort: false },
                        dispatch_filter: {},
                        init: function () {

                        },
                        orderbychange: function (mode) {
                            if (dialog.order_by_mode.name != mode) {
                                dialog.order_by_mode.name = mode;
                                dialog.order_by_mode.sort = false;
                            }
                            else {
                                if (dialog.order_by_mode.sort)
                                    dialog.order_by_mode.sort = false;
                                else
                                    dialog.order_by_mode.sort = true;
                            }

                        },
                        getSuggestDetail: function (list, filterItem) {
                            if (list) {
                                if (dialog.order_by_mode.name != "")
                                    list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                                var temp_list = list.filter(function (item, index, array) {
                                    var isOK = true,
                                        keys = Object.keys(filterItem);
                                    for (var i = 0; i < keys.length; i++) {
                                        var key = keys[i];
                                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                            if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                                isOK = false;
                                                break;
                                            }
                                        }
                                    }
                                    return isOK;
                                });
                                return temp_list;
                            } else {
                                return list;
                            }
                        },
                        checkSuggestQty: function (event, item) {
                            var target = event.currentTarget;
                            angular.element(target).addClass('is-focus');
                            $calculater.open(
                                function (num, dialog) {
                                    angular.element(target).removeClass('is-focus');
                                    dialog.hide();
                                    if ((+num) >= 0 && (+num) <= (+item.limit_qty))
                                        item.sug_qty = num;
                                    else
                                        $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert2'));
                                },
                                //按下右上角X後會呼叫此function
                                function (dialog) {
                                    angular.element(target).removeClass('is-focus');
                                    dialog.hide();
                                },
                                {
                                    defaultNum: item.sug_qty,
                                    decimal: false
                                });
                        },
                        back: function () {
                            dialog.hide();
                        },
                        submit_action: function (request) {
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                content: request,
                                success: function (data) {
                                    if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                        var msg = data.dispatch_msg.join("<br>")
                                        $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                            confirm_dialog.hide();
                                            enforce_dispatch_action(request, function () {
                                                search2(2, function () {
                                                    var str_array = [];
                                                    for (var i in request.dispatch_to) {
                                                        var str = request.need_dispatch_plot_detail.length +
                                                        $filter('translate')('A02.msg.sendWorkSuccess') + '[' + request.dispatch_to[i].machine_no + ']'
                                                        str_array.push(str);
                                                    }
                                                    $scope.$root.showToast(str_array.join("<br>"));
                                                    $scope.Mode = '';
                                                    selectWorkItemCount = 0;
                                                    $scope.select_all_bool = false;
                                                    $scope.selectRollback = 0;
                                                    QueryLotInfo_selected.clear();
                                                    //if ($scope.selectMachine)
                                                    //    $scope.selectMachine.dispatch_size = 0;
                                                    //console.log($scope.selectMachine);
                                                    //$scope.selectMachine.dispatch_size = 0;
                                                });
                                            });
                                        });
                                    }
                                    else {
                                        search2(2, function () {
                                            var str_array = [];
                                            for (var i in request.dispatch_to) {
                                                var str = request.need_dispatch_plot_detail.length +
                                                $filter('translate')('A02.msg.sendWorkSuccess') + '[' + request.dispatch_to[i].machine_no + ']'
                                                str_array.push(str);
                                            }
                                            $scope.$root.showToast(str_array.join("<br>"));
                                            $scope.Mode = '';
                                            selectWorkItemCount = 0;
                                            $scope.select_all_bool = false;
                                            $scope.selectRollback = 0;
                                            QueryLotInfo_selected.clear();
                                            //if ($scope.selectMachine)
                                            //    $scope.selectMachine.dispatch_size = 0;
                                            //console.log($scope.selectMachine);
                                            //$scope.selectMachine.dispatch_size = 0;
                                        });
                                    }
                                }
                            });
                        },
                        normal_confirm: function () {

                            dialog.submit_action(dialog.submit_data);
                            dialog.hide();
                        },
                        suggest_confirm: function () {
                            var check_length = 0;
                            if (work_mode == 0) {
                                for (var i in dialog.suggest_detail) {
                                    var op_no = dialog.suggest_detail[i].op_no;
                                    var lot_no = dialog.suggest_detail[i].lot_no;
                                    var sug_qty = dialog.suggest_detail[i].sug_qty;
                                    for (var j in dialog.submit_data.need_dispatch_plot_detail) {
                                        var org_op_no = dialog.submit_data.need_dispatch_plot_detail[j].op_no;
                                        var org_lot_no = dialog.submit_data.need_dispatch_plot_detail[j].plot_no;
                                        if (org_op_no == op_no && org_lot_no == lot_no)
                                            dialog.submit_data.need_dispatch_plot_detail[j].qty = sug_qty;
                                    }
                                }
                                dialog.submit_data.need_dispatch_plot_detail =
                                dialog.submit_data.need_dispatch_plot_detail.filter(function (item) {
                                    if (item.qty > 0)
                                        return item;
                                });
                                check_length = dialog.submit_data.need_dispatch_plot_detail.length;
                                if (dialog.submit_data.need_dispatch_plot_detail.length == 1) {
                                    if (dialog.submit_data.dispatch_to && dialog.submit_data.dispatch_to.length == 1) {
                                        dialog.submit_data.dispatch_to[0].qty = dialog.submit_data.need_dispatch_plot_detail[0].qty;
                                    }
                                }
                            }
                            else if (work_mode == 1) {
                                for (var i in dialog.suggest_detail) {
                                    var equipment_no = dialog.suggest_detail[i].equipment_no;
                                    var sug_qty = dialog.suggest_detail[i].sug_qty;
                                    for (var j in dialog.submit_data.dispatch_to) {
                                        var org_equipment_no = dialog.submit_data.dispatch_to[j].machine_no;
                                        if (equipment_no == org_equipment_no)
                                            dialog.submit_data.dispatch_to[j].qty = sug_qty;
                                    }
                                }
                                dialog.submit_data.dispatch_to =
                                dialog.submit_data.dispatch_to.filter(function (item) {
                                    if (item.qty > 0)
                                        return item;
                                });
                                check_length = dialog.submit_data.dispatch_to.length;
                            }
                            if (check_length > 0)
                                dialog.submit_action(dialog.submit_data);
                            else {
                                search2(2, function () {
                                    $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert1'));
                                    $scope.Mode = '';
                                    selectWorkItemCount = 0;
                                    $scope.select_all_bool = false;
                                    $scope.selectRollback = 0;
                                    QueryLotInfo_selected.clear();
                                    //if ($scope.selectMachine)
                                    //    $scope.selectMachine.dispatch_size = 0;
                                });
                            }
                            dialog.hide();
                        }
                    }
                }
            );
        }
        //
        $scope.mwlightColor = function (states) {
            var lightColor;
            if (states == '0') {
                lightColor = 'light-white';
            } else if (states == '1') {
                lightColor = 'light-green';
            } if (states == '2') {
                lightColor = 'light-blue';
            }
            return lightColor;
        };

        $scope.mlightColor = function (states) {
            var lightColor;
            if (states == 'H') {
                lightColor = 'red';
            } else if (states == 'M') {
                lightColor = 'yellow';
            } if (states == 'L') {
                lightColor = 'green';
            }
            return lightColor;
        };

        $scope.confirmEditSeq = function () {
            var content = {
                //machine_no: detail.EQUIPMENTNO,
                dispatch_plot_detail: []
            };
            $scope.QueryLotInfo.forEach(function (detail, index) {
                content.dispatch_plot_detail.push({
                    machine_no: detail.EQUIPMENTNO,
                    plot_no: detail.LotNo,
                    op_no: detail.OPNO,
                    WORKDATE: detail.WORKDATE,
                    seq: index
                });
                detail.seq = index;
            });
            $MMWService.sendToServer({
                //uri: 'ServicesSTD.Module_WIP.change_dispatch_seq_process',
                uri: 'ServicesSTD.Module_WIP.adjust_change_seq_process',
                content: content,
                success: function (data) {
                    $scope.$root.showToast($filter('translate')('A02.msg.seqChangeSuccess'));
                    $scope.Mode = '';
                    //20221011 modify by wangzy for M#0120393: 华禹彩印：派工作业处--已派工数据调整顺序点击确定后在当前界面无法再操作调整
                    //确认调整顺序好要将dispatch_size值重置为0
                    //$scope.selectMachine.dispatch_size = 0;
                    //initMachineExpend($scope.selectMachine);
                }
            });
        };

        $scope.cancelEditSeq = function () {
            $scope.QueryLotInfo = dispatched_detail_backup.slice();
            dis_date_separate_action();
            $scope.Mode = '';
            $scope.selectMachine = undefined;
            //if (sortablList) {
            //    sortablList.destroy();
            //    sortablList = undefined;
            //    dispatched_detail_backup = undefined;
            //    $scope.dispatched_detail = [];
            //}
        };

        $scope.selectRollback = 0;
        $scope.BatchMergeFlag = false;
        //$scope.QueryLotInfo_selected = [];
        var QueryLotInfo_selected = new Map(); //存放已勾选的列
        $scope.detailRollback = function (index, detail) {
            if (detail.status == '0') {
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
            }
            if ($scope.Mode != 'EditSeq') {
                if (detail.checked == 'Y') {
                    detail.checked = undefined;
                    $scope.selectRollback--;
                    //^_^ADD BY H-18036  20221206 FOR 是否显示批次合并按钮（取消勾选时）
                    QueryLotInfo_selected.delete(index); 
                    var QueryLotInfo_selected_delete = []; 
                    var detail_ = detail.WORKDATE + "," + detail.OPNO + "," + detail.EQUIPMENTNO; 
                    for (let value of QueryLotInfo_selected.values()) {
                        QueryLotInfo_selected_delete.push(value);  //将删减后的map push进数组 用于自身循环遍历
                    }

                    for (let i = 0; i < QueryLotInfo_selected_delete.length-1; i++) {
                        if (QueryLotInfo_selected_delete[i + 1] == QueryLotInfo_selected_delete[i]) { 
                            $scope.BatchMergeFlag = true;
                        } else {
                            $scope.BatchMergeFlag = false;
                            break;
                        }
                    }
                } else if (!detail.checked) {
                    detail.checked = 'Y';
                    $scope.selectRollback++;
                    //每勾选一行存放进map
                    var detail_ = detail.WORKDATE + "," + detail.OPNO + "," + detail.EQUIPMENTNO;
                    QueryLotInfo_selected.set(index, detail_);
                    //^_^ADD BY H-18036  20221205 FOR 批次合并按钮：选中同派工日期、同设备、同作业站，下方增加显示【批次合并】
                    isBatchMerge(index, detail_);
                }
                if ($scope.selectRollback == 0) {
                    //$scope.Mode = 'MachineExpend';
                    $scope.Mode = '';
                } else {
                    $scope.Mode = 'Rollback';
                }
            }

        };

        //^_^ADD BY H-18036  20221205 FOR 是否显示批次合并按钮（添加勾选时）
        function isBatchMerge(index, detail_) {
            for (let value of QueryLotInfo_selected.values()) {
                if (detail_ == value) {
                    $scope.BatchMergeFlag = true;
                } else {
                    $scope.BatchMergeFlag = false;
                    break;
                }
            }
        };
        //------------------------------------------
        //全选
        $scope.detailRollbackAll = function () {
            if ($scope.QueryLotInfo.length <= 0)
                return;
            for (var i in $scope.QueryLotInfo) {
                if ($scope.roll_back_all_bool)
                    $scope.QueryLotInfo[i].checked = '';
                else {
                    // 狀態 0 代表任務在智派工納入派工，不可勾選！
                    if ($scope.QueryLotInfo[i].status == '0')
                        $scope.QueryLotInfo[i].checked = '';
                    else
                        $scope.QueryLotInfo[i].checked = 'Y';
                }
            }
            if ($scope.roll_back_all_bool) {
                $scope.roll_back_all_bool = false;
                $scope.selectRollback = 0;
                QueryLotInfo_selected.clear();
                $scope.Mode = '';
            }
            else {
                $scope.roll_back_all_bool = true;
                $scope.Mode = 'Rollback';
                $scope.selectRollback = $scope.QueryLotInfo.length;
            }
        }
        //設備排序 select 開窗
        $scope.getEquipmentSortModeList = function () {
            $scope.$root.showSelect({
                label: "label",
                code: 'code',
                selectCode: $scope.equipment_sort_mode,
                list: $scope.equipment_sort_option_list,
                confirm: function (item, select_dialog) {
                    select_dialog.hide();
                    if ($scope.equipment_sort_mode != item.code)
                        $scope.equipment_sort_mode_change = true;
                    else
                        $scope.equipment_sort_mode_change = false;
                    $scope.equipment_sort_mode = item.code;
                    $scope.equipment_sort_mode_label = item.label;
                    EquipmentSortAction();
                }
            });
        }
        function EquipmentSortAction() {
            //模式改變 dis order score 歸零
            if ($scope.equipment_sort_mode_change) {
                for (var i in $scope.machine_detail)
                    $scope.machine_detail[i].dis_order_score = 0
            }
            switch ($scope.equipment_sort_mode) {
                // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                // 修正標準預設排序(case: 0,5,6,7)
                case "0":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
                case "1":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['times', 'machine_no'], true);
                    break;
                case "2":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['good_rate', 'machine_no'], true);
                    break;
                case "3":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['used_load', 'machine_no'], true);
                    break;
                case "4":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['used_load', 'machine_no']);
                    break;
                case "5":
                    var dis_data = $filter('filter')($scope.dispatch_detail, { checked: "Y" });
                    var has_score = false;
                    dis_data.forEach(function (item) {
                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                        equipment_data.forEach(function (eq_item) {
                            $scope.machine_detail.forEach(function (m_item) {
                                if (m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.times;

                                if (m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });

                    });
                    if ($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                    $scope.machine_detail = has_score
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
                case "6":
                    var dis_data = $filter('filter')($scope.dispatch_detail, { checked: "Y" });
                    var has_score = false;
                    dis_data.forEach(function (item) {
                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                        equipment_data.forEach(function (eq_item) {
                            $scope.machine_detail.forEach(function (m_item) {
                                if (m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.good_rate;
                                if (m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    if ($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                    $scope.machine_detail = has_score
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
                case "7":
                    var dis_data = $filter('filter')($scope.dispatch_detail, { checked: "Y" });
                    var has_score = false;
                    dis_data.forEach(function (item) {
                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                        equipment_data.forEach(function (eq_item) {
                            $scope.machine_detail.forEach(function (m_item) {
                                if (m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.equipment_seq;
                                if (m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    if ($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                    $scope.machine_detail = has_score
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'])
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
            }
            //console.log($scope.machine_detail);
        }
        //設備排序動作(改派 與 分量派)
        function EquipmentSortForDialogAction(dis_item, machine_data) {
            //init score for sort
            for (var i in machine_data)
                machine_data[i].dis_order_score = 0
            //console.log(data);
            if (typeof dis_item === "undefined")
                return;
            if (typeof machine_data === "undefined" || machine_data.length <= 0)
                return;

            switch ($scope.equipment_sort_mode) {
                // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                // 修正標準預設排序(case: 0,5,6,7)
                case "0":
                    machine_data = $filter('orderBy')(machine_data, ['machine_no']);
                    break;
                case "1":
                    machine_data = $filter('orderBy')(machine_data, ['times', 'machine_no'], true);
                    break;
                case "2":
                    machine_data = $filter('orderBy')(machine_data, ['good_rate', 'machine_no'], true);
                    break;
                case "3":
                    machine_data = $filter('orderBy')(machine_data, ['used_load', 'machine_no'], true);
                    break;
                case "4":
                    machine_data = $filter('orderBy')(machine_data, ['used_load', 'machine_no']);
                    break;
                case "5":
                    var dis_data = [dis_item];
                    var has_score = false;
                    dis_data.forEach(function (item) {
                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                        equipment_data.forEach(function (eq_item) {
                            machine_data.forEach(function (m_item) {
                                if (m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.times;

                                if (m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });

                    });
                    machine_data = has_score
                        ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')(machine_data, ['machine_no']);
                    break;
                case "6":
                    var dis_data = [dis_item];
                    var has_score = false;
                    dis_data.forEach(function (item) {
                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                        equipment_data.forEach(function (eq_item) {
                            machine_data.forEach(function (m_item) {
                                if (m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.good_rate;
                                if (m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    machine_data = has_score
                        ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')(machine_data, ['machine_no']);
                    break;
                case "7":
                    var dis_data = [dis_item];
                    var has_score = false;
                    dis_data.forEach(function (item) {
                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                        equipment_data.forEach(function (eq_item) {
                            machine_data.forEach(function (m_item) {
                                if (m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.equipment_seq;
                                if (m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    machine_data = has_score
                        ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'])
                        : $filter('orderBy')(machine_data, ['machine_no']);
                    break;
            }
            return machine_data;
        }
        //撤回
        $scope.confirmRollback = function () {
            $mdDialog.dialog('module/moduleA/program/A10/A10_Withdraw_menu.tmp.html', withdraw_dialog_controller);
        };
        //撤回開窗 controller
        function withdraw_dialog_controller(dialog) {
            var controller =
            {
                content: {},
                select_list: [],
                show_data: [],
                select_label: "",
                //select_machine_no: $scope.selectMachine.machine_no,
                isRunning: false,
                init: function () {
                    dialog.select_list = [
                        { "label": $filter('translate')('A02.with_draw.list_label_0'), "code": "0" },
                        { "label": $filter('translate')('A02.with_draw.list_label_1'), "code": "1" },
                        { "label": $filter('translate')('A02.with_draw.list_label_2'), "code": "2" },
                        { "label": $filter('translate')('A02.with_draw.list_label_3'), "code": "3" }];
                    dialog.content =
                    {
                        type:0,
                        need_dispatch_plot_detail: [],
                        dispatch_to: [],
                        work_mode: 0,
                        with_draw_mode: dialog.select_list[0].code,
                        dispatch_day: moment($scope.work_date).format('YYYY-MM-DD')
                    };
                    dialog.show_data = [];
                    dialog.isRunning = false;
                    dialog.check = 0; //确认时检查是否有为0的数量  0没有 
                    $scope.QueryLotInfo.forEach(function (detail) {
                        if (detail.checked == 'Y') {
                            if (detail.states != '0') {
                                dialog.isRunning = true;
                            }
                            var Qty_show = 0;
                            if (detail.Qty < detail.qty_not_in) {
                                Qty_show= detail.Qty
                            } else {
                                Qty_show= detail.qty_not_in
                            }
                            dialog.show_data.push({
                                WORKDATE: detail.WORKDATE,
                                EQUIPMENTNO: detail.EQUIPMENTNO,
                                EQUIPMENTNAME: detail.EQUIPMENTNAME,
                                OPNO: detail.OPNO,
                                OPNAME: detail.OPNAME,
                                LotNo: detail.LotNo,
                                MONO: detail.MONO,
                                ProductNo: detail.ProductNo,
                                ProductName: detail.ProductName,
                                ItemSpec: detail.ItemSpec,
                                Qty_everyday: detail.Qty, //当天派工数量
                                Qty_all_not_in: detail.qty_not_in, //总未进站数量 
                                Qty: Qty_show, //页面显示的数量  min（Qty_everyday，Qty_all_not_in）
                                StdDispStartTime: detail.StdDispStartTime,
                                StdDispEndTime: detail.StdDispEndTime,
                                //item_spec: detail.item_spec,
                                //mo_no: detail.wo_no,
                                //machine_no: $scope.selectMachine.machine_no,
                                //plot_start_time: detail.plot_start_time,
                                //plot_end_time: detail.plot_end_time
                            });
                        }
                    });
                    //dialog.select_label = dialog.select_list[0].label;
                },
                load_withdraw_list: function () {
                    $scope.$root.showSelect({
                        label: "label",
                        code: 'code',
                        selectCode: dialog.select_code,
                        list: dialog.select_list,
                        confirm: function (item, select_dialog) {
                            if (dialog.content.with_draw_mode != item.code) {
                                //mode change init dialog display qty
                                dialog.show_data.forEach(function (item) {
                                    item.qty = item.limit_qty;
                                });
                            }
                            select_dialog.hide();
                            dialog.select_label = item.label;
                            dialog.content.with_draw_mode = item.code;
                        }
                    });
                },
                checkWithdrawQty: function (event, item) {
                    var target = event.currentTarget;
                    angular.element(target).addClass('is-focus');
                    $calculater.open(function (num, dialog) {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                        if (num > 0 && num <= item.Qty_everyday && num < item.Qty_all_not_in)
                            item.Qty = num;
                        else
                            $scope.$root.showAlert($filter('translate')('A10.msg.msg1'));
                    },
                    //按下右上角X後會呼叫此function
                    function (dialog) {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                    },
                    {
                        defaultNum: item.qty,
                        decimal: false
                    });
                },
                back: function () {
                    dialog.hide();
                },
                confirm: function () {
                    //20220728 modify by wangzy for 0116240: 派工撤回报错
                    //for循环取值不对，应该取length才对，导致赋值need_dispatch_plot_detail异常
                    for (var i = 0; i < dialog.show_data.length; i++) {
                        //^_^ADD BY H-18036  20221206 FOR 校验数量是否正确
                        //if (dialog.show_data[i].Qty == 0 || dialog.show_data[i].Qty > dialog.show_data[i].Qty_everyday) {
                        //    $scope.$root.showAlert($filter('translate')('A10.msg.msg1'));
                        //} else if (dialog.show_data[i].Qty > dialog.show_data[i].Qty_all_not_in) {
                        //    $scope.$root.showAlert($filter('translate')('A10.msg.msg2'));
                        //}
                        //----------------------------------------------------------
                        dialog.content.need_dispatch_plot_detail.push({
                            plot_no: dialog.show_data[i].LotNo,
                            op_no: dialog.show_data[i].OPNO,
                            qty: dialog.show_data[i].Qty,
                            mo_no: dialog.show_data[i].MONO,
                            machine_no: dialog.show_data[i].EQUIPMENTNO,
                            plot_start_time: dialog.show_data[i].StdDispStartTime,
                            plot_end_time: dialog.show_data[i].StdDispEndTime,
                            dispatch_day: dialog.show_data[i].WORKDATE
                        });
                        if (dialog.show_data[i].Qty == 0) {
                            dialog.check = dialog.check+1;
                            //$scope.$root.showAlert($filter('translate')('A10.msg.msg1'));
                        }
                    }
                    var _fn = function () {
                        if (dialog.check != 0)
                            $scope.$root.showAlert($filter('translate')('A10.msg.msg1'));
                        else
                        $MMWService.sendToServer({
                            //uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                            uri: 'ServicesSTD.Module_WIP.adjust_dispatch_set_process',
                            content: dialog.content,
                            success: function (data) {
                                if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                    var msg = data.dispatch_msg.join("<br>")
                                    $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                        confirm_dialog.hide();
                                        enforce_dispatch_action(request, function () {
                                            search2(2, function () {
                                                $scope.$root.showToast(
                                                    $filter('translate')('A02.msg.rollbackSuccess.1')
                                                    + $scope.selectRollback
                                                    + $filter('translate')('A02.msg.rollbackSuccess.2')
                                                );
                                                $scope.Mode = '';
                                                $scope.selectRollback = 0;
                                                QueryLotInfo_selected.clear();
                                                $scope.roll_back_all_bool = false;
                                                //$scope.selectMachine.dispatch_size = 0;
                                                //var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                                //if (machine != undefined && machine.length > 0) {
                                                //    $scope.selectMachine = machine[0];
                                                //}
                                                //initMachineExpend($scope.selectMachine);
                                            });
                                        });
                                    });
                                }
                                else {
                                    search2(2, function () {
                                        $scope.$root.showToast(
                                            $filter('translate')('A02.msg.rollbackSuccess.1')
                                            + $scope.selectRollback
                                            + $filter('translate')('A02.msg.rollbackSuccess.2')
                                        );
                                        $scope.Mode = '';
                                        $scope.selectRollback = 0;
                                        QueryLotInfo_selected.clear();
                                        $scope.roll_back_all_bool = false;
                                        //$scope.selectMachine.dispatch_size = 0;
                                        //var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                        //if (machine != undefined && machine.length > 0) {
                                        //    $scope.selectMachine = machine[0];
                                        //}
                                        //initMachineExpend($scope.selectMachine);
                                    });
                                }
                            }
                        });
                    };
                    //if (dialog.isRunning) {
                    //    $scope.$root.showConfirm($filter('translate')('A02.msg.plot_still_running'), function (confirm_dialog) {
                    //        confirm_dialog.hide();
                    //        dispatch_info_calculation_process(dialog.content, function (data) {
                    //            if (data && data.msg != '') {
                    //                $scope.$root.showConfirm(data.msg, function (dialogType) {
                    //                    dialogType.hide();
                    //                    _fn();
                    //                });
                    //            }
                    //            else {
                    //                _fn();
                    //            };
                    //        });
                    //    });
                    //}
                    //else {
                    //    _fn();
                    //}
                    dispatch_info_calculation_process(dialog.content, function (data) {
                        if (data && data.msg != '') {
                            $scope.$root.showConfirm(data.msg, function (dialogType) {
                                dialogType.hide();

                                _fn();
                            });
                        }
                        else {
                            _fn();
                        };
                    });
                    dialog.hide();
                }
            };
            return controller;
        };
        //-------------------------------------------------------
        //取消撤回/移轉
        $scope.cancelRollback = function () {
            $scope.QueryLotInfo.forEach(function (detail) {
                detail.checked = undefined;
            });
            $scope.selectRollback = 0;
            QueryLotInfo_selected.clear();
            $scope.roll_back_all_bool = false;
            $scope.Mode = '';
            $scope.selectMachine = undefined;
            if (sortablList) {
                sortablList.destroy();
                sortablList = undefined;
                dispatched_detail_backup = undefined;
                $scope.dispatched_detail = [];
            }
        };

        //改派-----入口
        $scope.confirmTransfer = function () {
            var transferItem,
            
                feedback = function (data) {
                    dispatchItem = transferItem;
                    MachineListMode = '2';//轉移
                    machineList = EquipmentSortForDialogAction(dispatchItem, data);
                    $mdDialog.dialog(
                            'module/moduleA/program/A10/A10_MachineList.tmp.html',
                            MachineListController
                    );
                };
            // 取出勾選的已派生產批
            $scope.QueryLotInfo.forEach(function (detail) {
                if (detail.checked == 'Y') {
                    //var TransferQty = (detail.Qty < detail.qty_not_in) ? detail.Qty : detail.qty_not_in;
                    transferItem = detail;
                    transferItem.qty = detail.qty_not_in;
                    //transferItem.machine_no = $scope.selectMachine.machine_no;
                }
            });
            if (transferItem) {
                if ($scope.isLine == '1')
                    getLineMachineList(transferItem.LotNo, transferItem.OPNO, transferItem.WORKDATE, feedback);
                else
                    getMachineList($scope.value_e, feedback);
            }
        };

        // 批次合并
        $scope.confirmBatchMerge = function () {
            $mdDialog.dialog(
                'module/moduleA/program/A10/A10_batchMerge.tmp.html', function (dialog) {
                    return {
                        batchMerge_input: '',
                        back: function () {
                            dialog.hide();
                        },
                        confirm: function () {
                            var content = {
                                type:3,
                                work_mode: 3,
                                dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                                machine_detail: [{
                                    //machine_no: $scope.selectMachine.machine_no,
                                    dispatched_detail: []
                                }],
                                need_dispatch_plot_detail: []
                            };

                            $scope.QueryLotInfo.forEach(function (item) {
                                if (item.checked == 'Y') {
                                    item.Qty = (+item.Qty);
                                    item.batch_mark = dialog.batchMerge_input;
                                    item.CombinedTag = dialog.batchMerge_input;
                                    //content.machine_detail[0].dispatched_detail.push(item);
                                    content.machine_detail[0].dispatched_detail.push({
                                        plot_no: item.LotNo,
                                        mo_no: item.MONO,
                                        qty: item.Qty,
                                        machine_no: item.EQUIPMENTNO,
                                        op_no: item.OPNO,
                                        plot_start_time: item.StdDispStartTime,
                                        plot_end_time: item.StdDispEndTime,
                                        dispatch_day: moment(item.WORKDATE).format('YYYY-MM-DD'),
                                        batch_mark: item.batch_mark,
                                    });
                                    //content.need_dispatch_plot_detail.push(item);
                                    content.need_dispatch_plot_detail.push({
                                        plot_no: item.LotNo,
                                        mo_no: item.MONO,
                                        qty: item.Qty,
                                        machine_no: item.EQUIPMENTNO,
                                        op_no: item.OPNO,
                                        plot_start_time: item.StdDispStartTime,
                                        plot_end_time: item.StdDispEndTime,
                                        dispatch_day: moment(item.WORKDATE).format('YYYY-MM-DD'),
                                        batch_mark: item.batch_mark,
                                    });
                                }
                            });

                            $MMWService.sendToServer({
                                //uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                uri: 'ServicesSTD.Module_WIP.adjust_dispatch_set_process',
                                content: content,
                                success: function (data) {
                                    if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                        var msg = data.dispatch_msg.join("<br>")
                                        $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                            confirm_dialog.hide();
                                            enforce_dispatch_action(request, function () {
                                                dialog.hide();
                                                dialog.batchMerge_input = '';
                                            });
                                        });
                                    }
                                    else {
                                        dialog.hide();
                                        dialog.batchMerge_input = '';
                                    }

                                }
                            });
                        }
                    }
                }
            )
        };

        // 删除批次合并标记
        $scope.deleteBatchMergeMark = function (detail) {
            detail.CombinedTag = '';
            var content = {
                type:3,
                work_mode: 3,
                dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                machine_detail: [{
                    //machine_no: $scope.selectMachine.machine_no,
                    dispatched_detail: []
                }],
                need_dispatch_plot_detail: [detail]
            };
            content.machine_detail[0].dispatched_detail.push({
                plot_no: detail.LotNo,
                mo_no: detail.MONO,
                qty: detail.Qty,
                machine_no: detail.EQUIPMENTNO,
                op_no: detail.OPNO,
                plot_start_time: detail.StdDispStartTime,
                plot_end_time: detail.StdDispEndTime,
                dispatch_day: moment(detail.WORKDATE).format('YYYY-MM-DD'),
                batch_mark: detail.CombinedTag,
            });
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.adjust_dispatch_set_process',
                content: content,
                success: function (data, response) {
                    if (response.isSuccess) {
                        // 批次合併註記刪除成功
                        $scope.$root.showToast($filter('translate')('A02.msg.batchMerge_delete_success'));
                    }
                }
            });
        };

        //改派---->进入服务
        function MachineListConfirmTransfer(dialog) {
            var dispatchSum = 0;
            var need_dispatch_plot_detail = [];
            need_dispatch_plot_detail.push({
                plot_no: dispatchItem.LotNo,
                mo_no: dispatchItem.MONO,
                qty: dispatchItem.Qty,
                machine_no: dispatchItem.EQUIPMENTNO,
                op_no: dispatchItem.OPNO,
                plot_start_time: dispatchItem.StdDispStartTime,
                plot_end_time: dispatchItem.StdDispEndTime,
                AllToDoQty: dispatchItem.qty,
                dispatch_day:moment(dispatchItem.WORKDATE).format('YYYY-MM-DD'), //派工当时日期改到这里
            });
            //need_dispatch_plot_detail.plot_no = dispatchItem.LotNo;
            //need_dispatch_plot_detail.mo_no = dispatchItem.MONO;
            //need_dispatch_plot_detail.qty = dispatchItem.Qty;
            //need_dispatch_plot_detail.machine_no = dispatchItem.EQUIPMENTNO;
            //need_dispatch_plot_detail.op_no = dispatchItem.OPNO;
            //need_dispatch_plot_detail.plot_start_time = dispatchItem.StdDispStartTime;
            //need_dispatch_plot_detail.plot_end_time = dispatchItem.StdDispEndTime;
            //need_dispatch_plot_detail.AllToDoQty = dispatchItem.qty;
            //need_dispatch_plot_detail.dispatch_day = moment(dispatchItem.WORKDATE).format('YYYY-MM-DD'); //派工当时日期改到这里
            var content = {
                need_dispatch_plot_detail: need_dispatch_plot_detail,
                dispatch_to: [],
                work_mode: 2,
                type:2,
                transfer_day: moment(dialog.work_date).format('YYYY-MM-DD'),//要转移的目标日期
                //派工当时日期---------->18036 弃用 但为了保持dispatch_info_calculation_process方法不报错代码保留 后端服务有转换 不影响逻辑
                dispatch_day: moment($scope.work_date).format('YYYY-MM-DD')
            };
            dialog.machineList.forEach(function (machine, index) {
                if (machine.inputQty != undefined && machine.inputQty != 0) {
                    content.dispatch_to.push({ machine_no: machine.machine_no, qty: machine.inputQty });
                    dispatchSum += (+machine.inputQty);
                }
            });

            var _fn = function (request) {
                $MMWService.sendToServer({
                    //uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                    uri: 'ServicesSTD.Module_WIP.adjust_dispatch_set_process',
                    content: request,
                    success: function (data) {
                        //改派以後不會跳日
                        //$scope.work_date = dialog.work_date;
                        if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                            var msg = data.dispatch_msg.join("<br>")
                            $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                confirm_dialog.hide();
                                enforce_dispatch_action(request, function () {
                                    dialog.hide();
                                    search2(2, function () {
                                        $scope.$root.showToast(dispatchItem.LotNo + $filter('translate')('A02.msg.transSuccess'));
                                        $scope.Mode = '';
                                        $scope.selectRollback = 0;
                                        QueryLotInfo_selected.clear();
                                        //$scope.selectMachine.dispatch_size = 0;
                                        //var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                        //if (machine != undefined && machine.length > 0) {
                                        //    $scope.selectMachine = machine[0];
                                        //}
                                        //initMachineExpend($scope.selectMachine);
                                    });
                                });
                            });
                        }
                        else {
                            dialog.hide();
                            search2(2, function () {
                                $scope.$root.showToast(dispatchItem.LotNo + $filter('translate')('A02.msg.transSuccess'));
                                $scope.Mode = '';
                                $scope.selectRollback = 0;
                                QueryLotInfo_selected.clear();
                                //$scope.selectMachine.dispatch_size = 0;
                                //var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                //if (machine != undefined && machine.length > 0) {
                                //    $scope.selectMachine = machine[0];
                                //}
                                //initMachineExpend($scope.selectMachine);
                            });
                        }
                    }
                });
            };
            //----------------------------------------------------------------------------------------
            var qty_show = (dispatchItem.Qty < dispatchItem.qty) ? dispatchItem.Qty : dispatchItem.qty;
            if (content.dispatch_to.length == 0) {
                //尚未輸入派工數量
                $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
            } else if (dispatchSum <= qty_show) {
                dispatch_info_calculation_process(content, function (data) { //验证炉量
                    if (data && data.suggest_detail && data.suggest_detail.length > 0) {
                        OpenMachineSuggestListDialog(1, content, data.suggest_detail); //建议数量
                        dialog.hide();
                    }
                    else if (data && data.msg != '') {
                        $scope.$root.showConfirm(data.msg, function (dialogType) {
                            dialogType.hide();
                            _fn(content);
                        });
                    }
                    else {
                        _fn(content);
                    };
                });
            } else {
                $scope.$root.showAlert($filter('translate')('A10.msg.msg4') + qty_show);
            }
            //---------------------------------------------------------------------------------------------
        }

        $scope.dispatchedFilter = function (item) {
            return item.states != '0';
        };

        function dispatch_info_get_machine_detail(content, callback) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content: content,
                success: function (data) {
                    if (data.machine_detail && data.machine_detail.length > 0)
                        callback(data.machine_detail[0].dispatched_detail);
                    else
                        callback([]);
                }
            });
        }

        function dispatch_info_calculation_process(content, callback) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_info_calculation_process',
                content: content,
                success: function (data) {
                    if (callback)
                        callback(data);
                }
            });
        };

        //^_^ADD BY H-18036  20221201 FOR doflag
        $scope.ClickDoFlag = function () {
            if ($scope.do_flag == 1) {
                $scope.do_flag = 0;
            } else {
                $scope.do_flag = 1;
            }
        };

        //分頁
        $scope.getPages = function (list, PageConfig, filterItem) {
            if (list) {
                //console.log();
                if ($scope.order_by_mode.name != "")
                    list = $filter('orderBy')(list, $scope.order_by_mode.name, $scope.order_by_mode.sort);
                var temp_list = list.filter(function (item, index, array) {
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for (var i = 0; i < keys.length; i++) {
                        var key = keys[i];
                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                            if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                isOK = false;
                                break;
                            }
                        }
                    }
                    return isOK;
                });
                if (PageConfig) {
                    if (temp_list.length != 0) {
                        PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                        if (PageConfig.page >= PageConfig.total_page) {
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page * PageConfig.page_count;
                        return temp_list.slice(index, index + PageConfig.page_count);
                    } else {
                        PageConfig.total_page = 1;
                        PageConfig.page = 0;
                    }
                } else {
                    return temp_list;
                }
            } else {

                return list;
            }
        };
        function enforce_dispatch_action(request, feedback) {
            request.enforce_dispatch_msg = "1";
            $MMWService.sendToServer({
                //20240325 modify by wangqq for M#0159667: 【苏州劲山】【测试区】多日派工进行改派后，撤回生产批发现数量变多
                //当adjust_dispatch_set_process查询后存在返回dispatch_msg，应该调用adjust_dispatch_set_process
                uri: 'ServicesSTD.Module_WIP.adjust_dispatch_set_process',
                content: request,
                success: function (data) {
                    feedback();
                }
            });
        }
    }
    ];
});
